Printing Variables

In previous exercises we printed text using std::cout. Now let's look at how to print variable values.

When printing we can combine text and variables using the << operator:

int age = 25;
std::cout << "Age is: " << age << std::endl;

Notice several things:

  • Text must be in quotes: "Age is: "
  • Variables are written without quotes: age
  • We connect individual parts with the << operator

We can combine multiple variables in one output:

int height = 180;
int weight = 75;
std::cout << "Height: " << height << " cm, Weight: " << weight << " kg" << std::endl;

When printing numeric variables, numbers are automatically converted to text. No special conversion is needed.

Instructions

Print both variables on separate lines in the following format:

Whole number: 42
Decimal number: 3.14

Start programming for free

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

Or sign up with:

4/6

Printing Variables | Start Coder