C Output (printf)
To show something on the screen, C programs use the printf function from stdio.h. The name means print formatted: besides fixed text, it can print the values of variables in a format you choose.
Printing text
printf prints exactly what is between the double quotes. It does not add a new line by itself, so two calls without \n continue on the same line:
#include <stdio.h>
int main(void) {
printf("Hello ");
printf("World");
printf("\n");
printf("This is a new line.\n");
return 0;
}Hello World This is a new line.
Printing numbers
To print a value, put a format specifier in the text where the value should appear, and give the value after a comma. %d prints a whole number (an int):
#include <stdio.h>
int main(void) {
printf("%d\n", 42);
printf("Sum: %d\n", 7 + 5);
printf("%d apples and %d oranges\n", 3, 8);
return 0;
}42 Sum: 12 3 apples and 8 oranges
The values are used in order: the first %d takes the first value, the second %d the second. The Format Specifiers topic shows the codes for decimals, characters and text.
Special characters
Some characters cannot be typed directly inside quotes. They are written with a backslash, as an escape sequence:
| Escape | Meaning |
|---|---|
\n | new line |
\t | tab (jumps to the next column) |
\" | a double quote |
\\ | a backslash |
#include <stdio.h>
int main(void) {
printf("Name\tAge\n");
printf("Asha\t12\n");
printf("She said \"hi\".\n");
printf("C:\\temp\n");
return 0;
}Name Age Asha 12 She said "hi". C:\temp
To print a percent sign itself, write %%, because a single % starts a format specifier.
puts
puts("text") prints a line of text and adds the newline for you. It is handy for fixed text; use printf when you need values or no newline.
Practice exercises
- Print a small table of three fruits and their prices with
\tbetween the columns. - Print the sentence
50% of 8 is 4using%dfor the numbers and%%for the percent sign. - Print the path
C:\Users\studentexactly as written.