Printing with printf
Read · 1 of 6
printf prints exactly what you give it
It never adds a new line by itself: you write \n where you want one. \t jumps to the next tab stop, and \" prints a double quote.
To print a number, put %d in the text and the number after a comma: printf("%d\n", 7 + 3); prints 10.
Read this lesson as text
New lines, tabs and quotes inside text, and printing numbers with %d.
printf prints exactly what you give it
It never adds a new line by itself: you write \n where you want one. \t jumps to the next tab stop, and \" prints a double quote.
To print a number, put %d in the text and the number after a comma: printf("%d\n", 7 + 3); prints 10.
Watch the output build up
#include <stdio.h>
int main() {
printf("Score: ");
printf("%d\n", 40 + 2);
printf("7 + 3 = %d\n", 7 + 3);
printf("She said \"hi\"\n");
return 0;
}- Line 4: No \n, so the cursor stays at the end of this line.
- Line 5: %d is replaced by the value after the comma: 40 + 2 is worked out to 42.
- Line 6: Text inside the quotes is printed as it is; only %d is replaced.
- Line 7: \" prints a quote without ending the text.
No new line?
#include <stdio.h>
int main() {
printf("A");
printf("B\n");
printf("C\n");
return 0;
}What does this print?
- A B C
- AB C
- ABC
Show the answer
AB C Nothing ended the first line, so B is printed right after A.
Two numbers in one line
#include <stdio.h>
int main() {
printf("%d and %d\n", 2 * 5, 9 - 4);
return 0;
}What does this print?
- 10 and 5
- %d and %d
- 2 * 5 and 9 - 4
Show the answer
10 and 5 Each %d is filled in order by the values after the text.
Exercise: Print a staircase
Print these three lines:
*
**
***
Exercise: A quoted ticket
Print exactly these two lines. The gap is a tab (\t) and the quotes are part of the output:
Seat "A12"
Fare 250
Let C work out the fare: print 200 + 50 with %d.