Outline 3.1 Introduction
3.7 while Repetition Structure
A repetition structure allows the programmer to specify that a program should repeat an action while some condition remains true. The pseudocode statement
While there are more items on my shopping list Purchase next item and cross it off my list
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more informa- tion.
>>> value1 = raw_input( "Enter a number: " ) Enter a number: 3
>>> value2 = raw_input( "Enter a number: " ) Enter a number: 0
>>> print value1 + File "<stdin>", line 1 print value1 + ^
SyntaxError: invalid syntax >>> print value1 + value2 30
>>> print int( value1 ) / int( value2 ) Traceback (most recent call last): File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
Fig. 3.6 Fig. 3.6 Fig. 3.6
Fig. 3.6 Syntax and logic errors.
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more informa- tion. >>> if 1 < 2: ... pass ... Fig. 3.7 Fig. 3.7 Fig. 3.7
describes the repetition that occurs during a shopping trip. The condition, “there are more items on my shopping list” is either true or false. If it is true, the program performs the ac- tion “Purchase next item and cross it off my list.” This action is performed repeatedly while the condition remains true.
The statement(s) contained in the while repetition structure constitute the body (suite) of the while. The while structure body can consist of a single statement or multiple statements. Eventually, the condition should evaluate to false (in the above example, when the last item on the shopping list has been purchased and crossed off the list). At this point, the repetition terminates, and the program executes the first statement after the repetition structure.
Common Programming Error 3.6
A logic error, called an infinite loop (the repetition structure never terminates), occurs when an action that causes the condition in the while structure to become false is missing from
the body of a while structure. 3.6
Common Programming Error 3.7
Spelling the keyword while with an uppercase W, as in While (remember that Python is a case-sensitive language), is a syntax error. All of Python’s reserved keywords, such as
while, if, elif and else, contain only lowercase letters. 3.7 As an example of a while structure, consider a program segment designed to find the first power of 2 larger than 1000. Suppose variable product has been created and initial- ized to 2. When the following while repetition structure finishes executing, product will contain the desired answer:
product = 2
while product <= 1000: product = 2 * product
At the start of the while structure, product is 2. The variable product is multi- plied by 2, successively taking on the values 4, 8, 16, 32, 64, 128, 256, 512 and 1024. When the value of product equals 1024, the while structure condition, product <= 1000, evaluates to false. This terminates the repetition—the final value of product is 1024. Pro- gram execution continues with the next statement after the while structure.
The flowchart of Fig. 3.8 illustrates the flow of control in the while structure that cor- responds to the preceding while structure. Once again, note that (besides small circles and arrows) the flowchart contains a rectangle symbol and a diamond symbol.
Fig. 3.8 Fig. 3.8 Fig. 3.8
Fig. 3.8
while
repetition structure flowchart.product <= 1000 true product = 2 * product
Imagine a bin of empty while structures that can be stacked and nested with other con- trol structures to implement an algorithm’s flow of control. The empty rectangles and dia- monds are then filled in with appropriate actions and decisions. The flowchart shows the repetition. The flowline emerging from the rectangle wraps back to the decision that is tested each time through the loop until the decision becomes false. Then, the while structure exits and control passes to the next statement in the program.
3.8 Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)
To illustrate how algorithms are developed, we solve several variations of a class-averaging problem. Consider the following problem statement:
A class of ten students took a quiz. The grades (integers in the range 0 –100) for this quiz are available. Determine the class average on the quiz.
The class average is equal to the sum of the grades divided by the number of students. The algorithm for solving this problem requests each of the grades, performs the averaging cal- culation and prints the result.
Using pseudocode, we list the actions to be executed and specify the order in which these actions should be executed. We use counter-controlled repetition to input the grades oneatatime. Thistechnique usesavariablecalled a
counter
tocontrol thenumber of times a set of statements executes. Repetition terminates when the counter exceeds 10. In this section, we present a pseudocode algorithm (Fig. 3.9) and the corresponding program (Fig. 3.10). In the next section, we show how to develop pseudocode algorithms. Counter- controlled repetition often is called definite repetition because the number of repetitions is known before the loop begins executing.Note the references in the algorithm to the variables total and counter. In the program of Fig. 3.10, the variable total (line 5) accumulates the sum of a series of values, while the variable counter counts—in this case, it counts the number of user-entered grades. Variables that store totals normally are initialized to zero.
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten Input the next grade
Add the grade into the total Add one to the grade counter
Set the class average to the total divided by ten Print the class average
Fig. 3.9 Fig. 3.9 Fig. 3.9
Fig. 3.9 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.
Good Programming Practice 3.3
Initialize counters and totals. 3.3
Lines 5–6 are assignment statements that initialize total to 0 and gradeCounter to 1. Line 9 indicates that the while structure should continue as long as grade-
Counter’s value is less than or equal to 10.
Lines 10–11 correspond to the pseudocode statement Input the next grade. Function
raw_input displays the prompt “Enter grade:” on the screen and accepts user input. Line 11 converts the user-entered string to an integer.
Next, the program updates total with the new grade entered by the user—line 12 adds grade to the previous value of total and assigns the result to total.
Then, the program increments the variable gradeCounter to indicate that a grade has been processed. Line 13 increments gradeCounter by one, allowing the condition in the while structure to evaluate to false and terminate the loop.
Line 16 executes after the while structure terminates and assigns the results of the