9. Control Structures

9.2. Flow of Control: Repetition Structures

As we saw in Chapter 3, a repetition structure is a control structure that repeats a statement or sequence of statements. Many programming tasks require a repetition structure. Consider some examples.

 

 

 

You’re working for the National Security Agency trying to decipher se- cret messages intercepted from foreign spies, and you want to count the number of times a certain letter, “a,” occurs in a document containing N characters. In this case, you would want to employ something like the following (pseudocode) algorithm:

,,

 

 

 

J

You’re working for a caterer who wants to number the invitations to a client’s wedding, so you need to print the numbers between 1 and 5000

 

on the invitation cards (it’s a big wedding)! In this case, you want to go through each number, 1 to 5000, and simply print it out:

,,

 

J

You are helping the forest service in Alaska to track the number of black bear sightings, and you want to compute the average number of sight- ings per month. Suppose the user enters each month’s count at the keyboard, and uses a special number, say, 9999, to signify the end of the sequence. However, 9999 should not be figured into the average. This example differs a bit from the preceding ones, because here you don’t know exactly how many numbers the user will input:

,,

 

 

 

 

 

 

 

J

We repeat the process of reading numbers and adding them to a run- ning total “until the number read is 9999.”

Student records are stored in a file and you want to calculate Erika Wilson’s current GPA. Here we need to perform a repetitive process— searching through the file for Erika Wilson’s record—but again we don’t know exactly how many times to repeat the process:

,,

 

 

 

J

As these examples suggest, two types of loops are used: counting loops and non-counting loops. Counting loops are used whenever you know in advance exactly how many times an action must be performed. Non- counting loops are used when the number of repetitions depends on some condition—for example, the number of data items input from the keyboard or the input of a particular record from a file.