Printf exercise solution
In this article, we do some exercises. Write a program to print the below text using the printf function.
Remember that the output should exactly look something like this. And you should maintain all the punctuation, special characters, everything you have to maintain exactly shown in this text message. So, you can either use a single printf function or multiple printf functions. So, you can do it whichever way you want, no problem with that.
Let’s do that. Now, let me first use printf for each and every line. Let me write printf and open the bracket and write the given text. In printf, you have to write your message in double-quotes, close the bracket, and give the semicolon. Complete this step for every line.
The solution is given in Figure 1.
- David says, “programming is fun!”
In the first statement, we are printing double-quotes. So, we put a backslash escape character(\) before the double quote. We did it in a previous article. And let’s use \n to go to the new line.
printf(“David says, \“programming is fun !\”, \n”);
- **Conditions apply, “Offers valid until tomorrow”
Here, also give the backslash escape character(\) before the double quote. Let’s use \n here as well.
printf(“**Conditions apply, \“Offers valid until tomorrow\”\n”);
- C:\My computer\My folder
In this example, there is one backslash escape character before the M character. So, this is considered as \M. \M is not a valid escape sequence. If you want to print that backslash, you can use \\ escape sequence.
printf(“C:\\My computer\\My folder\n”);
- D:/My documents/My file
This string is fine, no problem. Let’s use \n here.
printf(“D:/My documents/My file\n”);
- \\\\ Today is holiday\\\\
In this example, here we are printing backslash. That’s why we have to use the escape character that is backslash(\) for each and every backslash which we want to print and, in the end, give \n.
printf(“ \\ \\ \\ \\ Today is holiday \\ \\ \\ \\\n”);
- This is a triple quoted string “”” This month has 30 days “””
In this example, there is a triple quoted string, and here there are multiple double quotes, so we have to use backslash for every double quote here. And after that at the end \n.
printf(“This is a triple quoted string \”\”\” This month has 30 days \”\”\”\n”);
Now this resolves all the issues. Let’s run this program. Here we got the correct output (Shown in Figure 2), so we got exactly the way we wanted.
If you are confused, just spend some time with the code and try to understand the syntaxes.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1