Text and Numbers
printf can print numbers too, and it can even calculate with them. The f at the end of its name stands for formatted. The text in quotes is a format string, and it can contain format specifiers: placeholders that start with %. The specifier %d means "a whole number goes here". You write the number itself after the text, separated by a comma:
printf("%d\n", 42);This prints:
42The letter d stands for decimal: the number is printed in the decimal system, as usual. Write numbers in code without spaces and commas: 1250, not 1 250 or 1,250.
Instead of a number, you can write a calculation after the comma. C works it out first and prints the result. A text in quotes, however, is printed exactly as it is:
printf("%d\n", 5 + 3);
printf("5 + 3\n");This prints:
8
5 + 3You add with +, subtract with - and multiply with a star * (not with the letter x). As in math, multiplication goes before addition, and parentheses change the order:
printf("%d\n", 2 + 3 * 4);
printf("%d\n", (2 + 3) * 4);This prints:
14
20Division / has a surprise in store in C, so it waits for the next lesson.
The format string can contain text around %d. The value is printed in place of %d, and the rest of the text stays as it is:
printf("The game has %d levels.\n", 12 + 8);This prints:
The game has 20 levels.The spaces around %d are part of the text, so you have to write them yourself: "The game has%dlevels.\n" would print The game has20levels.
Common mistakes:
- A forgotten value after the comma: for
printf("The game has %d levels.\n");, the compiler doesn't run the program and reports the errormore '%' conversions than data arguments(more%specifiers than values). - A calculation written into the text:
printf("The game has 12 + 8 levels.\n");printsThe game has 12 + 8 levels.C doesn't calculate inside quotes. - A missing comma:
printf("%d\n" 42);ends with the errorexpected ')'.
Instructions
The second printf prints the text 27 + 2. Change it, so that C adds up the numbers and prints 29: in the quotes, replace the text with %d\n, and after the closing quote, add a comma and the calculation 27 + 2.
Now turn the result into a whole sentence. Change the second printf, so that the program prints:
27 students and 2 teachers are going on the trip.
That's 29 people in total.Let C keep calculating the 29 with %d, and don't forget the spaces around it.
A zoo ticket costs 12 dollars. Add a line that prints how much the tickets cost for everyone together, so that the program prints:
27 students and 2 teachers are going on the trip.
That's 29 people in total.
Tickets in total: 348 dollarsLet C work out the price as (27 + 2) * 12. The parentheses make sure that the people are added up first, and only then multiplied by the price.
Start programming for free
4/7