Skip to main content

Section 2.6 Displaying Two Messages

You can put as many statements as you like in the main function. For example, to display more than one line of output we could use two cout statements:
Listing 2.6.1.
Notice that the first print statement has another << after the string it is printing to separate the string from the next piece of data to be output. That data is endl which means "end of line" - it will ensure that anything that whatever comes next in the output will appear on the next line (like hitting Enter while typing). Thus we get two lines of output.
Also notice that the program omits the return 0; at the end of main. In C++, it is optional to include that line - if the programmer does not include it, it is silently added at the end of main. It is also possible to return a value other than 0. When a program returns 0, that indicates to the operating system that the program completed successfully. To indicate an error occurred, the programmer can return any non-zero value. This is a C++ feature we will not be exploring in this book.
Lastly, it also demonstrates that you can put comments at the end of a line as well as on lines all by themselves. The code before the // is not part of the comment.
Now let us look at a similar program that lacks an endl in its print statement:
Listing 2.6.2.
Without the endl the second print statement will output to the same line as the first one. The output has a space after the comma because there is an extra space inside the quotation marks of the first string. Without that space, the output would say β€œGoodbye,from C++”.
You can output as many things as you like in one statement of code by chaining together << operators. That can include as many (or few) endl as you like.
Listing 2.6.3.

Insight 2.6.1.

The number of lines of output is not controlled by the number of cout statements, but rather by the presence of endls.

Checkpoint 2.6.1.

On how many separate lines will the 7’s be printed?
#include <iostream>
using namespace std;

int main() {
  cout << 7 << endl;
  cout << 7;
  cout << 7;
  cout << 7;
}
  • There is an "endl" statement, implying that a new line is created.
  • "endl" creates one new line. The first line will say 7, while the second will print 777.
  • In C++, you must make sure to say "endl" every time you’d like to create a new line.
  • In C++, you must make sure to say "endl" every time you’d like to create a new line.

Checkpoint 2.6.2.

Construct a main function that prints β€œSnap!” on the first line, β€œCrackle!” on the third line, and β€œPop!” on the seventh line. You might not use all of endl blocks provided.
Desired output:
Snap!

Crackle!


Pop!

Checkpoint 2.6.3.

Construct a main function that prints β€œHello, world!” so that β€œHello,” and β€œworld!” are printed on two separate lines. You will not use all of the blocks.
You have attempted of activities on this page.