Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 2.5 Outputting Variables

You can output the value of a variable using the same commands we used to output simple values. The program below 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
Run the code. After observing the output, try modifying the assignment statements to make a different time!
Listing 2.5.1. This program outputs the current time, according to the values you provide for hour and minute.
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:
Listing 2.5.2. This program does the same thing as the previous, but the print statements have been condensed to one line. This is better style.
On one line, this program outputs a string, two integers, a character, and the special value endl. Very impressive!

Checkpoint 2.5.1.

What prints when the following code is run?
int main() {
  char a;
  char b;
  a = 'z';
  b = '8';
  cout << "a";
}
  • The string, not the variable, a will be printed.
  • b will not be printed.
  • The cout statement prints a, not the value of the variable a.
  • z is the value of a and 8 will not be printed
  • Nothing! There will be a compile error!
  • There is no type mismatch, so there will not be a compile error.

Checkpoint 2.5.2.

Now, what prints?
int main() {
  char a;
  char b;
  a = 'z';
  b = '8';
  cout << b;
}
  • The string a will not be printed.
  • The string b will not be printed.
  • z is the value of a and 3 will not be printed.
  • 8 is the value of b will be printed!
  • Nothing! There will be a compile error!
  • There is no type mismatch, so there will not be a compile error.

Checkpoint 2.5.3.

And now, what prints?
int main() {
  int x;
  char y;
  x = '3';
  y = 'e';
  cout << 'y';
}
  • Take a look at the code again.
  • Take a look at the code again.
  • Take a look at the code again.
  • Take a look at the code again.
  • Nothing! There will be a compile error!
  • There is a type mismatch, so there will be a compile error!

Checkpoint 2.5.4.

Checkpoint 2.5.5.

Construct a main function that assigns “Hello” to the variable h, then prints out h’s value.
You have attempted 1 of 6 activities on this page.