2. First Programs
Taste of Things to Come: Iteration
The last program of this introductory chapter will show you how to do repetitions in C++. As we have already discussed, statements in a program are executed in sequence. However, there are special statements that can change the order of execution. One such statement is the iteration statement.
The main iteration statement in C++ is
called for
. At first sight, the for
statement may appear slightly
intimidating since it is a bit more complicated to write than the statements we
have seen thus far. Nevertheless, let us take a look at it:
Note that the for
statement is not ended by a semicolon symbol.
int main() { cout << "I sing" << endl; for (double i=1;i<=3;i++) { cout << "Sail sail" << endl; cout << "my little boat" << endl; } cout << "While I catch my fish" << endl; }
As you can see, the word for
is followed by a pair
of parentheses (i.e. round brackets) enclosing a rather arcane looking piece of
code. For the time being, we will leave the magic of this incantation
undisturbed and bring your attention only to the number 3 that signifies how
many repetitions there are. This for
statement thus demands that three
iterations (i.e. repetitions) be performed.
A sequence of statements inside a pair of braces
(i.e. curly brackets) is called a statement block.
A for
statement controls the statement block by repeating it as many
times as has been specified. This statement block will be repeated (i.e.
iterated) three times. In each iteration, the statements in a statement block
will be executed in the usual order, one by one.
This is what the program outputs:
STDOUT: I sing Sail sail my little boat Sail sail my little boat Sail sail my little boat While I catch my fish
You might be wondering why we didn't provide a more detailed explanation of the for
statement in this chapter.
Unfortunately, it is impossible to provide a more detailed explanation at this stage without too many oversimplifications that put a reader at real risk of misunderstanding the concepts involved. Also, the elements of such explanation are mostly useless at this stage and would be left unapplied for too many pages of this book.
The only important things to remember are that the for
statement is used for iteration, that the number of iterations is specified by a particular number (more precisely, by an expression), and that the for
statement should not be ended by a semicolon.
While curiosity is a quality to be encouraged, today's world has made people too accustomed to instant gratification. Instead, we would suggest to our programming apprentices to practice another very fine and useful human quality: being patient.