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

Printing Variables

A number on its own doesn't say much in the output. But with <<, you can send several parts to the output one after another, text and variables, and print a whole sentence:

int age = 15;
std::cout << "I am " << age << " years old.\n";

This prints:

I am 15 years old.

std::cout prints the parts from left to right: text in quotes exactly as it's written, and for a variable without quotes, its value. So watch the quotes: std::cout << "age"; prints the word age, not the value of the variable.

<< doesn't add any spaces between the parts. You have to write the spaces yourself, inside the quotes. That's why "I am " has a space at the end and " years old.\n" at the start. Without them, the words stick to the number:

int age = 15;
std::cout << "I am" << age << "years old.\n";

This prints:

I am15years old.

One statement can print several variables:

int height = 168;
int weight = 55;
std::cout << "Height: " << height << " cm, weight: " << weight << " kg\n";

This prints:

Height: 168 cm, weight: 55 kg

Instructions

  1. 1

    Run the program. It prints Home3. Change the text in quotes so that the program prints Home: 3.

  2. 2

    Below it, print the variable away the same way: Away: 1

  3. 3

    Finally, print this line with one std::cout statement. Don't write the numbers 90, 3 and 1 into the text; take them from the variables:

    Score after 90 minutes: 3:1
Back

2/11

  1. 1. Creating Variables
  2. 2. Printing Variables
  3. 3. Initialization and Assignment
  4. 4. Data Types
  5. 5. Arithmetic
  6. 6. Integer Division
  7. 7. Quiz: Integer Division
  8. 8. Updating Variables
  9. 9. Joining Text
  10. 10. Quiz: Joining Text
  11. 11. Summary
Next

Try it yourself

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