Printf exercise solution
How to print text in a new line?
Let’s discuss how to print the text “Today is a great day” in a new line.
First, let’s type printf(“Today is a great day!”); now, let’s see how this goes. Let’s run.
Look at Figure 1, so this is not our expected output. Here we want to push this text (“Today is a great day”) to the next line.
By this, you can understand the behavior of the printf function. Printf never causes the cursor to move to the next line. So, unless you mention the printf to do that.
Let’s give a couple of spaces here and Run.
In the output section you see, the first printf statement is executed in the first line, and after that, when the next printf is executed, the printing continues from there onwards (Figure 2). So, that’s the behavior that you can notice from this code. Both printf statements are printed in one line. Second printf statement didn’t enter the new line.
How to tell the printf to push the cursor to the next line? So, you can tell by passing some code to the printf function. And that code is ‘n,’ n means new line or line feed.
But you cannot simply write n here. What happens if you write n? So, it will be treated just like another character. If you run this, it will print the character ‘n.’
To give a special meaning to this character, you have to use an escape character. And in ‘C,’ the escape character is a backslash (\). Let’s give a backslash character.
Now, \n is called an escape sequence. An escape sequence is a collection of two characters. One is a backslash, and another one is code. Here n is a code to push the cursor to the new line. So, you can use this escape sequence wherever you want; it need not be at the end. You can use it anywhere you want.
Let’s Run the code once again. We now got the expected output, as shown in Figure 4.
Here what happened was, when printf printed all these characters (Hello World!), then it saw a special sequence(\n) here, which means it will treat the character n as a code to push the cursor to the second line or new line.
So, like this in ‘C,’ there are various escape sequences. You can give this escape sequence anywhere you want.
For example, look at Figure 5. After the characters w, o, r, and l, we give escape character \n.
You can see the output(Figure 5). So, after character w, \n is treated as an escape sequence to push the cursor to the new line. That’s why the cursor went to the new line, and after that, it printed o, and again the cursor went to the new line it printed r, and so on.
In the following article, let’s discuss some more escape sequences available in the ‘C’ programming language.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1