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.
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.
On one line, this program outputs a string, two integers, a character, and the special end of line character. Very impressive!
- a
- The string, not the variable, a will be printed.
- b
- b will not be printed.
- z
- The cout statement prints a, not the value of the variable a.
- 8
- z is the value of a and will not be printed
- Nothing! There will be a compile error!
- There is no type mismatch, so there will not be a compile error.
Q-3: What prints when the following code is run?
int main () {
char a;
char b;
a = 'z';
b = '8';
cout << "a";
}
- a
- The string a will not be printed.
- b
- The string b will not be printed.
- z
- z is the value of a and will not be printed.
- 8
- 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.
Q-4: Now, what prints?
int main () {
char a;
char b;
a = 'z';
b = '8';
cout << b;
}
- x
- Take a look at the code again.
- y
- Take a look at the code again.
- 3
- Take a look at the code again.
- e
- 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!
Q-5: And now, what prints?
int main () {
int x;
char y;
x = '3';
y = 'e';
cout << 'y';
}
-
Q-6: Match the variable initialization to its correct type.
Try again!
- x = 2
- int
- y = "2"
- string
- z = '2'
- char
Construct a main function that assigns “Hello” to the variable h, then prints out h’s value.
More to Explore
From cppreference.com
cout and escape sequences