You could alter the program to display two sentences on separate lines using a single printf() statement.
#include <stdio.h>
int main(void)
{
printf("This is a test.\nThis is the second line.\n");
return 0;
}
After the first sentence and at the end of the text, you've inserted the characters \n
.
The combination \n
is an escape sequence that represents a newline character.
This causes the output cursor to move to the next line.
The backslash (\) indicates the start of an escape sequence.
The character following the backslash indicates what character the escape sequence represents.
\n
is for newline.
The code above generates the following result.
Because a backslash itself is a special character,
to specify a backslash in a text string, use two backslashes: \\
.
#include <stdio.h>
int main(void)
{
printf("\"This is a test.\"\nShakespeare\n");
return 0;
}
The double quotes are output because you use escape sequences for them in the string.
Shakespeare appears on
the next line because there is a \n
escape sequence following the \"
.
You can use the \a
escape sequence in an output string to sound a beep
to signal something interesting or important.
The code above generates the following result.
#include <stdio.h>
int main(void)
{
printf("Be careful!!\n\a");
return 0;
}
The \a
sequence represents the "bell" character.
The code above generates the following result.
The following table shows all the escape sequences that you can use.
Escape sequence | Description |
---|---|
\n | Represents a newline character |
\r | Represents a carriage return |
\b | Represents a backspace |
\f | Represents a form-feed character |
\t | Represents a horizontal tab |
\v | Represents a vertical tab |
\a | Inserts a bell (alert) character |
\? | Inserts a question mark ( ?) |
\" | Inserts a double quote ( ") |
\' | Inserts a single quote ( ') |
\\ | Inserts a backslash (\) |
The following code shows how to use the escape character listed in the table.
#include <stdio.h> // Include the header file for input and output
//from w w w . ja va2 s . co m
int main(void)
{
printf("Hi there!\n\n\nThis program is a bit\n");
printf(" longer than the others.\n");
printf("\nThis is a test.\n\n\n\a\a");
printf("Hey!! What was that???\n\n");
printf("\t1.\tA control character?\n");
printf("\n\t\t\b\bThis is a new line?\n\n");
return 0;
}
The code above generates the following result.