< previous page page_258 next page >

Page 258
Count-Controlled Loops
A count-controlled loop uses a variable we call the loop control variable in the loop test. Before we enter a count-controlled loop, we have to initialize (set the initial value of) the loop control variable and then test it. Then, as part of each iteration of the loop, we must increment (increase by 1) the loop control variable. Here's an example:
loopCount = 1;                     // Initialization
while (loopCount <= 10)           // Test
{
    .
    .                              // Repeated actions
    .
    loopCount = loopCount + 1;     // Incrementation
}
Here loopCount is the loop control variable. It is set to 1 before loop entry. The While statement tests the expression
loopCount <= 10
and executes the loop body as long as the expression is TRUE. The dots inside the compound statement represent a sequence of statements to be repeated. The last statement in the loop body increments loopCount by adding 1 to it.
Look at the statement in which we increment the loop control variable. Notice its form:
variable = variable + 1;
This statement adds 1 to the value of the variable, and the result replaces the old value. Variables that are used this way are called counters. In our example, loopCount is incremented with each iteration of the loopwe use it to count the iterations. The loop control variable of a count-controlled loop is always a counter.
We've encountered another way of incrementing a variable in C++. The incrementation operator (++) increments the variable that is its operand. The statement
loopCount++;
has precisely the same effect as the assignment statement

 
< previous page page_258 next page >