Valid XHTML 1.1

Firefox Download Button

Loops in C++

Carlos Moreno

Fear is what keeps us going
– Jody Loffredo

Repetition Structures

Like most programming languages, C++ provides flow control structures to implement repetition. These control structures, generally known as loops, allow us to write blocks of code that are executed a given number of times, or simply executed until certain condition is met. The advantage is that we need not write that block of code many times in the source code. Instead, we set up a loop to make the block execute as many times as required.

A simple example of this idea is a program that executes a given task, and then asks the user if they want to try again for a different input. Notice that we are not talking about an if statement to check if we should repeat the procedure — if the user chooses to try again, the idea is that the program will again ask the user if they want to try again, and so on, for as long as the user indicates.

Loops can be categorized into two basic types: for loops, and while loops. For loops are related to the notion of a loop that is executed a given number of times — as in, a known number of times; and by known, we mean known a priori, following a very simple inspection of the algorithm. While loops, on the other hand, are related to the idea of a loop that is executed until certain condition happens; in general, we do not know a priori how many times a while loop will execute, and in some cases we can not even determine it even by carefully inspecting the code (an example is a loop that asks the user if they want to try again — we can not know how many times that loop will execute; we will only know it after it executes and we look at the user input).

While loops

The syntax for a while loop in C++ is the following:

while (condition)
{
    statement(s);
}

The statement or block of statements enclosed in the curly braces is called the body of the loop.

A simple concrete example is shown below:

while (number <= 0)
{
    cout << "Number must be positive. Please try again: " << flush;
    cin >> number;
}

The above example illustrates one of the typical uses of while loops: validation of user input.

Everything discussed in the Conditional execution tutorial for conditions applies here as well.

Another variation of the while loop in C++ is the do – while loop. The do – while loop has the syntax shown below:

do
{
    statement(s);
}
while (condition);

Notice that this one requires a semicolon after the condition at the bottom of the loop, whereas the while loop, in general, must not have a semicolon (for the same reasons explained for the if statement at the end of that section in the Conditional execution tutorial).

There are some situations where a semicolon could be placed after the condition in a one-liner while loop; however, I will not discuss such situations at this time.

The important difference between the while loop and the do – while loop is that in the while loop, the condition is evaluated first, and thus, the block of statements might be executed zero times (if the condition is false when entering the loop). The do – while loop, however, is guaranteed to execute at least once, given that we first execute the statements, and then check the condition to see if we should repeat execution.

Brainteaser: Given two loops, a while loop, and a do – while loop, with identical conditions, identical statements in the body of the loop, and identical user input (in case the loop is controlled by user input), how many times will the do – while loop execute, with respect to the while loop? (same number of times? twice as many? One more time?)

Think very carefully about this detail — the answer that our intuition gives us is most likely the incorrect answer.

Firefox Download Button

Infinite loops

Infinite or endless loops refer to a loop that — presumably by error — executes indefinitely. We notice that in the case of the while loops (in both forms), it is necessary that the body of the loop modify at least one of the elements that affect the condition; furthermore, it must do that in a way that it makes the condition become false at some point. Otherwise, if the condition was true at the beginning, then it will be true the second time (since the body of the loop did not modify anything that makes the condition change). But it will also be true the third time, and the fourth time, and so on. Thus, execution of the body of the loop will never stop repeating.

An example of an infinite loop is shown below:

number = -1;
while (number <= 0)
{
    cout << "Error -- number must be positive" << endl;
}

Since the body of the loop does not modify number, then it will always be -1 when evaluating the condition, and thus the condition will always evaluate to true. The loop never stops executing.

As I mentioned, this is in general due to an error in the program; in the above example, perhaps an oversight from the programmer — we intended to display an error message and prompt the user for a new value to replace the invalid negative value; but we forgot to input the new value, causing the loop to become an infinite loop.

The typical symptom of an infinite loop is that the program freezes; thus, when observing this behaviour, the first thing that you should check in your program is each and every loop.

An immediate sign that a loop may be an infinite loop is the fact that the body of the loop does not modify any of the variables involved in the condition. This is not a requirement for the loop to be infinite; but it is easy to check, and if we observe that that is the case, then we know for sure that the loop may be infinite (typically, what happens is that either the loop executes zero times, or it executes indefinitely — that's why we say that it may be an infinite loop).

The example shown below is also an infinite loop, even though the body of the loop does modify one of the variables involved in the condition:

number = 1;
while (number > 0)
{
    number = number + 1;
}

Brainteaser: Conceptually, the above is an infinite loop; however, in practice it is not an infinite loop. Why?

Firefox Download Button

For loops

For loops are used when we know up-front or can trivially determine the number of times that a loop will execute. The syntax of a for loop in C++ is as follows:

for (initialization; condition; increment step)
{
    statement(s);
}

For loops require a control variable that typically counts how many times the loop has executed. This control variable is initialized in the first section of the loop definition; usually, it is also declared there, in which case, the scope of that variable is restricted to the body of the loop (that is, the variable that we declare in the initialization section of the for loop “ceases to exist” after the closing curly brace enclosing the body of the loop).

An example of a for loop that prints a fixed message five times is shown below:

for (int i = 0; i < 5; i++)
{
    cout << "Executing the body of the loop" << endl;
}

Notice that the control variable, i, is being declared in the loop definition. We could use this control variable inside the body of the loop (and in many cases, we do); but if we attempt to use it after the loop ended, we get a compiler error, since the variable is no longer visible at that point.

Notice that the above loop should be read as follows: for i equals 0, while i is less than 5, execute the body and increase i by 1 (the expression i++ has the side-effect of increasing the value of i by 1).

In essence, the for loop in C++ is a disguised version of a while loop. We could write the above loop as follows, and it would have the exact same behaviour:

int i = 0;
while (i < 5)
{
    cout << "Executing the body of the loop" << endl;
    i++;
}

However, it is considered a good practice to use a for loop in situations where the loop is executed a given number of times, as opposed to being executed until something happens.

An example of a for loop where the control variable is used inside the body of the loop is shown below, where the loop prints a table of the squares of the numbers from 1 to 5 (the second power of the numbers):

cout << "N\tN^2\n";
for (int i = 1; i < 5; i++)
{
    cout << i << 't' << i*i << endl;
}
  Firefox Download Button