|
|
|
|
|
|
|
A common task in a loop is to keep track of the number of times the loop has been executed. For example, the program fragment below reads and counts input characters until it comes to a period. (inChar is of type char; count is of type int.) The loop in this example has a counter variable; but the loop is not a count-controlled loop because the variable is not being used as a loop control variable. |
|
|
|
|
|
|
|
|
count = 0; // Initialize counter
cin.get(inChar); // Read the first character
while (inChar != .)
{
count++; // Increment counter
cin.get(inChar); // Get the next character
} |
|
|
|
|
|
|
|
|
The loop continues until a period is read. After the loop is finished, count contains one less than the number of characters read. That is, it counts the number of characters up to, but not including, the sentinel value (the period). Notice that if a period is the first character, the loop body is not entered and count contains a zero, as it should. We use a priming read here because the loop is sentinel-controlled. |
|
|
|
|
|
|
|
|
The counter variable in this example is called an iteration counter because its value equals the number of iterations through the loop. |
|
|
|
 |
|
 |
|
|
Iteration Counter A counter variable that is incremented with each iteration of a loop. |
|
|
|
|
|
|
|
|
According to our definition, the loop control variable of a countcontrolled loop is an iteration counter. However, as you've just seen, not all iteration counters are loop control variables. |
|
|
|
|
|
|
|
|
Another common looping task is to sum a set of data values. Notice in the example below that the summing operation is written the same way, regardless of how the loop is controlled. |
|
|
|
|
|
|
|
|
sum = 0; // Initialize the sum
count = 1;
while (count <= 10)
{
cin >> number; // Input a value
sum = sum + number; // Add the value to sum
count++;
} |
|
|
|
|
|