|
|
|
|
|
|
|
We initialize sum to 0 before the loop starts so that the first time the loop body executes, the statement |
|
|
|
|
|
|
|
|
adds the current value of sum (0) to number to form the new value of sum. After the entire code fragment has executed, sum contains the total of the 10 values read, count contains 11, and number contains the last value read. |
|
|
|
|
|
|
|
|
Here count is being incremented in each iteration. For each new value of count, there is a new value for number. Does this mean we could decrement count by 1 and inspect the previous value of number? No. Once a new value has been read into number, the previous value is gone forever unless we've saved it in another variable. You'll see how to do that in the next section. |
|
|
|
|
|
|
|
|
Let's look at another example. We want to count and sum the first 10 odd numbers in a data set. We need to test each number to see if it is even or odd. (We can use the modulus operator to find out. If number % 2 equals 1, number is odd; otherwise, it's even.) If the input value is even, we do nothing. If it is odd, we increment the counter and add the value to our sum. We use a flag to control the loop because this is not a normal count-controlled loop. In the following code segment, all of the variables are of type int except the Boolean flag, lessThanTen. |
|
|
|
|
|
|
|
|
count = 0; // Initialize event counter
sum = 0; // Initialize sum
lessThanTen = TRUE; // Initialize loop control flag
while (lessThanTen)
{
cin >> number; // Get the next value
if (number % 2 == 1) // Is the value odd?
{
count++; // Yes--Increment counter
sum = sum + number; // Add value to sum
lessThanTen = (count < 10); // Update loop control flag
{
} |
|
|
|
|
|
|
|
|
In this example, there is no relationship between the value of the counter variable and the number of times the loop is executed. We could have written the While expression this way: |
|
|
|
|
|
|
|
|
but this might mislead a reader into thinking that the loop is countcontrolled in the normal way. So, instead, we choose to control the loop with the flag lessThanTen, to emphasize that count is incremented only |
|
|
|
|
|