In the previous section, we displayed strings on the screen using the printf function.
You can display strings on the screen as much as you like using the printf function.
"By the way, how will the following program be displayed?"
#include <stdio.h>
int main(void)
{
printf("Hello");
printf("world");
return 0;
}
The results were as follows:
I think you'll notice one significant thing when you see this.
It is not line-broken.
"This way, we're limited to simply displaying them side-by-side, which is very inconvenient."
It may wrap at the right edge of the screen, but...
Is it not possible to force a line break at the point I want?
It's incredibly inconvenient that I can't make line breaks when displaying text on the screen.
Therefore, C has a feature that allows you to insert a line break at the desired position.
To perform a line break in a C language program, you use an
escape sequence.
Escape sequences are special characters used to perform control functions that cannot be displayed on the screen.
One of the escape sequences is
\n, which is intended to represent a newline.
【Escape sequence】
Control characters used to perform actions that cannot be displayed on the screen.
If you include it within a string that displays the character '\n',
It will wrap and display a new line where there is a \n on the screen.
"Note that overseas, a backslash (\\) is used instead of the yen symbol (¥)."
This is because Japanese computers use characters that differ slightly from the fonts used on computers overseas.
However, no problems arise because both are treated as the exact same character internally.
The following program demonstrates how to create a line break using the escape sequence \n.
#include <stdio.h>
int main(void)
{
printf("Hello\n");
printf("world\n");
return 0;
}
The results of this program's execution are as follows:
You can use line breaks wherever you like and as many as you like.
For example, you can rewrite the program as follows, and the result will be the same.
#include <stdio.h>
int main(void)
{
printf("Hello\nworld\n");
return 0;
}
It might be a little unclear, but there's a \n in the middle.
Often, it's easier to read if you insert a line break after each line.
Going forward, line breaks will be added at the end of each line unless there's a specific reason not to.
There are other escape sequences, but only a limited number are commonly used.
Besides line breaks,
\t is often used for indentation.
The following program demonstrates indentation using tabs.
#include <stdio.h>
int main(void)
{
printf("Windows\tMicrosoft\n");
printf("MacOS\tApple\n");
return 0;
}
The results of this program's execution are as follows:
Windows Microsoft
MacOS Apple
The second letter is vertically aligned.