|
©1994-2003 Kevin Boone |
| Home Section index K-Zone home | C++ tutorial (under construction) |
|
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
The 'while' loop is simple and flexible
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. |