You are here

Variations on Counting

10 February, 2015 - 11:32

In the following example, the integer variable age is said to be controlling the loop (that is the flag). We can assume that age has a value provided earlier in the program. Because the while structure is a test before loop; it is possible that the person's age is 0 (zero) and the first time we test the expression it will be false and the action part of the loop would never be executed.

Example 14.7: C++ source code: while as a counting loop

while (0 < age)   {   cout « "\nI love candy!";   age--;   } 

Consider the following variation assuming that age and counter are both integer data type and that age has a value:

Example 14.8: C++ source code: while as a counting loop

counter = 0; while (counter  <  age)   {   cout « "\nI love corn chips!";   counter++;   } 

This loop is a counting loop similar to our first counting loop example. The only diference is instead of using a literal constant (in other words 5) in our expression, we used the variable age (and thus the value stored in age) to determine how many times to execute the loop. However, unlike our first counting loop example which will always execute exactly 5 times; it is possible that the person's age is 0 (zero) and the first time we test the expression it will be false and the action part of the loop would never be executed.