Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

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

    Score: 3:1
  2. 2

    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
  3. 3

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

    3 + 1 = 4 goals
Back

3/13

  1. 1. Creating a Variable
  2. 2. Initialization and Assignment
  3. 3. Several Values in One printf
  4. 4. Decimal Numbers
  5. 5. Characters
  6. 6. Calculating
  7. 7. Whole-Number Division
  8. 8. Quiz: Whole-Number Division
  9. 9. Getting a Decimal Result
  10. 10. Quiz: A Decimal Result
  11. 11. Changing Variables
  12. 12. Constants
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.