You are here

Counting Loops

10 February, 2015 - 11:23

The examples above are for an event controlled loop. The flag updating is an event where someone decides if they want the loop to execute again. Often the initialization sets the fag so that the loop will execute at least once.

Another common usage of the while loop is as a counting loop. Consider:

Example 14.5: C++ source code: while loop that is counting

counter = 0; while (counter  <  5) { cout « "\nI love ice cream!"; counter++; } 

The variable counter is said to be controlling the loop. It is set to zero (called initialization) before entering the while loop structure and as long as it is less than 5 (five); the loop action will be executed. But part of the loop action uses the increment operator to increase counter's value by one. After executing the loop five times (once for counter's values of: 0, 1, 2, 3 and 4) the expression will be false and the next line of code in the program will execute. A counting loop is designed to execute the action (which could be more than one statement) a set of given number of times. In our example, the message is displayed five times on the monitor. It is accomplished my making sure all four attributes of the while control structure are present and working properly. The attributes are:

  • Initializing the fag
  • Test expression
  • Action or actions
  • Update of the fag

Missing an attribute might cause an Infinite loop or give undesired results (does not work properly).