Chapter 5 Review: Iteration

Count-controlled loop

Counting loops repeat a pre-specified number of times. In other words, the number of iterations is controlled by a "count" whose value is known before the loop starts.

Example problem: Find the average age at which the Presidents of the U.S. have taken office.

Best implemented with a for statement.

Example statement: for (int president = 1; president <= NumberOfPresidents; President ++)
 
 

Event-controlled loop (a.k.a.Conditional loop)

A loop which repeats until a particular condition or "event" arises.

Example problem: Given the current population growth rate, how long until there are 10 billion people on the planet.

Best implemented with a while statement.

Example statement: while (population <= LimitPopulation)
 
 

Sentinel-controlled loop (a kind of event loop)

An event-controlled loop used for processing a set of data, where the loop terminates when a data item with a particular "sentinel" value is processed.

Example problem: Read a list of ages until a negative age is encountered.

Best implemented with a while statement.

Example statement: while (age > 0)
 
 

Flag-controlled loop (a kind of event loop)

An event-controlled loop used for repeating some action whose termination depends on the occurrence of some real-time event. Usually this event is monitored by another process which communicates event completion by setting a boolean value, or "flag."

Example problem: A water treatment unit which repeats adding a certain chemical until a pH meter indicates that the target pH value has been attained.

Best Implemented with a while statement.

Example statement: while (NeedsMoreChemical)
 
 

Endfile loop (a kind of event loop)

A specific application of an event loop used to read data items from an external file of unknown length.


Loop Construction

Every loop has four parts: initialization, testing, body, increment.  The way in which these four parts interact is what creates the loops behavior. When constructing a loop, verify that all four parts are properly specified.  You need to answer these four questions:
  1. What is the loop's starting value? (initialization)
  2. How is the loop termination determined? (testing)
  3. How does the loop control variable get incremented (increment)
  4. What statements are to be repeated? (body)


Initialization:       int countPeople = 0;
Testing:              while (countPeople < PeopleLimit)
                      {
Body:                   Age = getInt("enter your age");
                        TotalYears = TotalYears + Age;
Increment:              countPeople = countPeople + 1;
                      }