2.5. 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.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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 value endl. Very impressive!

Construct a main function that assigns “Hello” to the variable h, then prints out h’s value.

You have attempted 1 of 8 activities on this page