A computer program consists of a sequence of instructions, one after the other, called statements. The basic structure of any program can be represented like this:
Begin
Statement
Statement
Statement
.....
End
C++ insists that all statements end with a semicolon. You will remember from the last section that all statements should end with a semicolon (;). The reason is that C++ is tolerant of different layouts. If you chose to put several statements on one line, then the semicolons would be the only way in which C++ would be able to separate them:
x++;cout<<"This is my first program";x+2;if(x>3){y=x;}x--;
All right, that was a rather extreme example.
<< is used to pass an item from right to left. In the example we saw above,
cout << "This is my first program.";
the string "This is my first program." is passed to the routine cout which prints things on the screen. << is quite versatile. You can pass items along a chain of << operators:
cout << "Humpty Dumpty " << "sat on a wall.";
"sat on a wall." is passed to "Humpty Dumpty " and the two strings are both passed to cout which produces:
Humpty Dumpty sat on a wall.
You will notice that there was a space between Dumpty and the double quotation mark. C++ had to be told that Dumpty was a separate word. If you had missed out the space:
cout << "Humpty Dumpty" << "sat on a wall.";
you would have got the following result:
Humpty Dumptysat on a wall.
You are not allowed to spread a string over two lines simply by putting a line break in the middle of it. Something like this would produce an error when you tried to compile it:
cout << "This string is on two different lines."
If you do want a string to appear on two different lines, then there are two ways of doing it.
cout << "Before the break\nAfter the break";
will produce:
Before the break
After the break
on the screen.
cout << "Before the break" << endl << "After the break";
would produce the same result as you saw above. However,
cout << "Before the break endl After the break";
just produces
Before the break endl After the break
on the screen.
You can put as many of these together as you like to skip over several lines. You can even mix them:
cout << "Before the break" << endl << endl << endl
<< "After the break";
would give three line breaks (i.e. two blank lines - try it!) between the first group of words and the second. A similar effect could be achieved with
cout << "Before the break\n\n\nAfter the break";
or even
cout << "Before the break\n\n" << endl << "After the break";