Chapter 1 · Lesson 3 of 5
03. Numbers and sums
C can do sums. Show the answers with printf and %d, the placeholder for a whole number.
To show a number, put %d in the text where it should go, then the number after a comma. %d is a placeholder: printf swaps it for the number.
#include <stdio.h>
int main() { printf("I have %d mangoes\n", 12); printf("7 + 5 = %d\n", 7 + 5); printf("%d times %d is %d\n", 6, 7, 6 * 7); return 0;}It shows
I have 12 mangoes 7 + 5 = 12 6 times 7 is 42
C works out the sum first, then prints the answer. Use + and - as usual, * to multiply and / to divide. With several %ds, the numbers after the text fill them in order.
Your turn
1Steps
- 1A school bus has 4 rows of 9 seats. Print
Seats:and the number of seats, worked out by C with*. - 2Then print
Hours in a week:and24 * 7, also worked out by C.
Write it in main.c. If it reads input, put the answers in Program input, under the terminal.
Use: printf()
Starting code
The editor starts empty. Copy this into it to begin, or write your own from scratch.
#include <stdio.h>
int main() { printf("Seats: \n"); return 0;}2Expected output
It should show
Seats: 36 Hours in a week: 168
3Hints
Stuck? Open one hint at a time: each gives a bit more help.
Hint 1
Put %d where the number goes, and the sum after a comma.
Hint 2
The first line is printf("Seats: %d\n", 4 * 9);
Hint 3
The second is made the same way, with 24 * 7 after the comma.