12. Nested Loops

for Loops in Detail

We are finally about to describe for loops in detail, in case that you have not figured it all out by yourself. Let us analyze this for loop:

for (int i=0; i<17; i++) 
    ...

In a for loop like the one above, the loop control variable i will be assigned all values from 0 to 16 through the loop's iterations. Enclosed between the parentheses are three parts separated by semicolons:

  • The first part is called the initialization, here given as int i=0. The initialization is executed only once at the beginning of the execution of the loop and it is not executed again during iterations.
  • The second part is called the condition, here given as i<17. The condition is examined at the start of each iteration. If the condition is not satisfied (i.e if it is false), the loop will be ended immediately. The condition is examined at the start of the first iteration, too, so if the condition is false at the start of the first iteration, no iterations will be executed at all. Also, the condition is examined only at the start of an iteration.
  • The third part is called the afterthought, here given as i++. This part is executed at the end of each iteration. It is commonly used to advance the value of the control variable so that the control variable is assigned the succeeding value.

When a control variable is incremented by one in each iteration, for example by using expression i++ as an afterthought, then we will say that the loop's step equals one.

The statement block controlled by the loop is called the body of the loop. The body of the loop is repeatedly executed while the condition is true. It can be said that the loop iterates the execution of its body.

How would one make a loop that counts backwards? Here is an example:

for (int i=7; i>=3; i=i-1)
    cout << i << endl;

The result is:

7
6
5
4
3
Warning! The expression i=i-1 can be written in a shortened form as i-=1. But the shortest and most common way to decrement a variable by one is by writing i--. This shortest form utilizes the decrement operator. The decrement operator can also be written like this: --i.

Writing a for loop with a decrement operator is a much more common practice:

for (int i=7; i>=3; i--)
    cout << i << endl;

This for loop has a step equal to -1.

To print out all the positive multiples of a number three that are smaller than 20, we could use a for loop having a step of three, like this:

for (int k=3; k<20; k+=3)
    cout << k << endl;

It outputs:

3
6
9
12
15
18

To print out squares of all natural numbers that have squares less than 60, we could write:

for (int n=1; n*n<60; n++)
    cout << n*n << endl;

It outputs:

1
4
9
16
25
36
49