2.6. Outputting Variables

You can output the value of a variable using the same commands we used to output simple values. After observing the output, try inputting your own time!

This program outputs the current time, according to the values you provide for hour and minute.

time Output
 1#include <iostream>
 2
 3int main () {
 4    using std::cout;
 5
 6    int hour = 11;
 7    int minute = 59;
 8    char colon = ':';
 9
10    cout << "The current time is "
11         << hour
12         << colon
13         << minute
14         << '\n';
15}

This program creates two integer variables named hour and minute, and a character variable named colon. It assigns appropriate values to each of the variables and then uses a series of output statements to generate the following:

The current time is 11:59

When we talk about “outputting a variable,” we mean outputting the value of the variable. To output the name of a variable, you have to put it in quotes. For example: cout << "hour"; The output of this statement is as follows.

hour

As we have seen before, you can include more than one value in a single output statement, which can make the previous program more concise:

This program does the same thing as the previous, but the print statements have been condensed to one line. This is better style.

Condensing The Code
 1#include <iostream>
 2
 3int main () {
 4    int hour = 11;
 5    int minute = 59;
 6    char colon = ':';
 7
 8    std::cout << "The current time is "
 9              << hour << colon << minute << '\n';
10}

On one line, this program outputs a string, two integers, a character, and the special end of line character. Very impressive!

Q1

What prints when the following code is run?

int main () {
  char a;
  char b;
  a = 'z';
  b = '8';
  cout << 'a';
}

Q2

Now, what prints?

int main () {
  char a;
  char b;
  a = 'z';
  b = '8';
  cout << b;
}

Q3

And now, what prints?

int main () {
  int x;
  char y;
  x = '3';
  y = 'e';
  cout << 'y';
}

Q4

Match the variable initialization to its correct type.

Q5

Construct a main function that assigns "Hello" to the variable h, then prints out h's value.

  1. #include <iostream>
  2. #include <string>
  3. char h;
  4. h = "Hello";
  5. h = Hello;
  6. int main () {
  7. std::cout << "Hello";
  8. std::cout << 'h';
  9. std::cout << h;
  10. std::string h;
  11. }

More to Explore