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 = 7

As 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 2

Spaces 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

Below, print the score with one printf with two %d. Take the numbers from the variables home and away:

Score: 3:1

On the next line, print this text. Use one printf with three values: minute, home and away. Don't write the numbers into the text:

After 90 minutes: 3:1

Finally, print the number of goals as a calculation. The third value is home + away:

3 + 1 = 4 goals

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/11