Several Values in One printf
So far, each printf has printed one value. But one printf can print several. Write a %d into the text for each value, and the values after the text, separated by commas:
int apples = 4;
int pears = 3;
printf("%d apples and %d pears\n", apples, pears);
printf("%d + %d = %d\n", apples, pears, apples + pears);This prints:
4 apples and 3 pears
4 + 3 = 7As you know from the previous lesson, the text in quotes is the format string: it says what the line will look like. Each %d in it is a format specifier, a placeholder for one value. printf fills them in order: the first value goes into the first %d, the second value into the second %d, and so on. A value can be a variable, a number, or a whole calculation such as apples + pears.
So the order of the values matters. If you swap them, they swap places in the output too:
int home = 2;
int away = 1;
printf("Home %d, away %d\n", away, home);This prints:
Home 1, away 2Spaces are part of the format string, too. printf prints it exactly as it's written, so "Score:%d" prints Score:3, and "Score: %d" prints Score: 3.
The number of format specifiers must match the number of values. If a value is missing, the compiler reports more '%' conversions than data arguments: there are more placeholders than values. If there is one value too many, it reports data argument not used by format string.
Instructions
- 1
Below, print the score with one
printfwith two%d. Take the numbers from the variableshomeandaway:Score: 3:1 - 2
On the next line, print this text. Use one
printfwith three values:minute,homeandaway. Don't write the numbers into the text:After 90 minutes: 3:1 - 3
Finally, print the number of goals as a calculation. The third value is
home + away:3 + 1 = 4 goals