C Newline in Output
In this page:
The \n Escape Sequence
The \n escape sequence represents a newline character, and placing it inside a string tells printf to move the cursor to the beginning of the next line at exactly that point in the output.
Example: The \n Escape Sequence
#include <stdio.h>
int main() {
printf("Line one\nLine two");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multiple Lines in One printf
A single printf call isn't limited to one line -- multiple \n sequences can appear within the same string literal, each one starting a new line as the string is printed.
Example: Multiple Lines in One printf
#include <stdio.h>
int main() {
printf("Line one\nLine two\nLine three");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Newlines Across Multiple printf Calls
Newlines don't have to come from a single printf call; several consecutive calls can build up multi-line output together, with each \n in any of them starting a fresh line.
Example: Newlines Across Multiple printf Calls
#include <stdio.h>
int main() {
printf("Line one\n");
printf("Line two\n");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Newline vs No Newline
Without an explicit \n, consecutive printf calls print their text immediately next to each other on the same line, which is a common source of confusing output for beginners expecting automatic line breaks.
Example: Newline vs No Newline
#include <stdio.h>
int main() {
printf("Hello");
printf("World");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Platform Differences in Line Endings
The C standard library handles the translation between \n and the operating system's actual line-ending convention automatically when writing to a text-mode stream, so the same \n works correctly across Linux, macOS, and Windows.
Example: Platform Differences in Line Endings
#include <stdio.h>
int main() {
printf("This works the same on Linux, macOS, and Windows\n");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: