New Lines in C Output
Using \n for New Lines
In C, the escape sequence `\n` is used to insert a new line.
It moves the cursor to the beginning of the next line when printing text.
#include <stdio.h>
int main(void) {
printf("Line 1\n");
printf("Line 2\n");
return 0;
}
Line 1 Line 2
Printing Multiple Lines in One printf
You can insert multiple `\n` characters in one `printf` to break lines.
This is useful for formatting output cleanly.
#include <stdio.h>
int main(void) {
printf("First Line\nSecond Line\nThird Line\n");
return 0;
}
First Line Second Line Third Line
Using puts for Convenience
`puts` prints a string and automatically appends a newline. It's handy when you just want to print a line of text.
#include <stdio.h>
int main(void) {
puts("Line 1");
puts("Line 2");
return 0;
}
Line 1 Line 2
Buffering: Why Newlines Matter
`stdout` is often line-buffered when connected to a terminal. Printing a newline typically flushes the buffer so text appears immediately.
If you print without a newline and need immediate output, call `fflush(stdout);`.
#include <stdio.h>
int main(void) {
printf("Processing...");
fflush(stdout); // ensure the text appears right away
// ... do some work here ...
printf(" done\n");
return 0;
}
Processing... done
Platform Note: Newline Translation
In C source, you always use `\n` for a newline. On some systems (e.g., Windows), the C library may translate `\n` to the platform's native line ending when writing in text mode.
You generally do not need to write `\r\n` yourself when using standard I/O; just use `\n`.