Print Text in C
Using printf to Display Text
The `printf` function from the `stdio.h` library is the most common way to display output in C.
Text literals must be enclosed in double quotes ("...").
Add a newline `\n` to move the cursor to the next line (many terminals are line-buffered, so a trailing newline helps ensure output appears promptly).
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}
Hello, World!
Printing Multiple Texts
You can print multiple pieces of text by calling `printf` multiple times, or combine them in one call.
Combining into one call is often clearer and can be slightly more efficient.
#include <stdio.h>
int main(void) {
printf("Hello, ");
printf("C Language!\n");
// Combined
printf("Hello, %s!\n", "C Language");
return 0;
}
Hello, C Language! Hello, C Language!
Escaping Quotes and Special Characters
Use escapes to print special characters:
• `\n` newline, `\t` tab, `\\` backslash, `\"` double quote.
#include <stdio.h>
int main(void) {
printf("She said: \"C is fun!\"\\n means newline.\n");
printf("Column A\tColumn B\n");
return 0;
}
She said: "C is fun!"\n means newline. Column A Column B
Printing Text Stored in Variables
Use the `%s` format specifier to print C strings (null-terminated `char` arrays).
#include <stdio.h>
int main(void) {
char name[] = "Alice";
printf("Hello, %s!\n", name);
return 0;
}
Hello, Alice!
Alternatives: puts and putchar
`puts(const char*)` prints a string followed by a newline automatically.
`putchar(int)` prints a single character.
#include <stdio.h>
int main(void) {
puts("Hello with puts"); // newline added automatically
putchar('O');
putchar('K');
putchar('\n');
return 0;
}
Hello with puts OK
Best Practices
• Prefer including a trailing `\n` in your output for clean lines and timely flushing.
• Use format specifiers (like `%s`) rather than manual concatenation when inserting variable content.
• Use `puts` for simple whole-line messages (it always appends a newline).
• Remember that `printf` returns the number of characters printed; you can check it for errors if needed.