C++ tutorial: while


A loop is a section of program that is repeated
It is very often necessary to cause part of the program to repeat a number of times. The number of repetitions may be known in advance by the programmer, or it might not. An example of a loop where the number of repetitions is not known in advance is one that continues until the user provides some input.

Various types of loop are available
C/C++ offers a number of loop constructs. Strictly speaking, only one type is actually necessary: the others can be constructed from it. However, it often makes a program easier to read if a type of loop is used which reflects the 'intuitive' way of structuring it.

The 'while' loop is simple and flexible
The 'while' loop causes part of the program to be repeated as long as some condition is true. The basic structure of the loop is:

while (condition)
      {
      //The statements in the braces are
      // executed while 'condition' is true
      }

Again, note the use of indentation to indicate to the reader that the statements in the curly braces are part of the loop. 'Condition' is any test that can be 'true' or 'false', just as for the 'if' and 'if...else' branch instructions.

Have a look at the program box1.cpp. This program draws a simple 'box' of asterisks, producing an output like this:

**********
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********

Because the middle part of the box is repeated identically, this is a good candidate for making into a loop. In box1.cpp the loop is controlled by this statement:

     while (i <= 8)

meaning: repeat the statements in the loop as long as 'i' is less than or equal to '8'. The other statement which may be new to you is:

     i++;

which means 'add 1 to i'. This notation is exactly equivalent to

     i = i + 1;

The '++' notation, although rather terse and uninformative, is almost universally used by C/C++ programmers, so it's as well to become familiar with it.

Because 'i' gets incremented (i.e., '1' added) in every pass of the loop, the loop will terminate after 8 passes.

In practice, it is more readable to use the 'for' loop when the loop should be executed a pre-defined number of times. This is described next.

©1994-2003 Kevin Boone, all rights reserved