Skip to main content
ICT
Lesson A12 - Iterations
 
Main   Previous Next
 

C. Conditional Loop Strategies page 5 of 18

  1. This section will present a variety of strategies that assist the novice programmer in developing correct while loops. The problem to be solved is described first.

    Problem statement:

    A program will read integer test scores from the keyboard until a negative value is typed in. The program will drop the lowest score from the total and print the average of the remaining scores.

  2. One strategy in designing a while loop is to think about the following four sections of the loop: 1) initialization, 2) loop boundary, 3) contents of the loop and 4) the state of variables after the loop.

    1. Initialization - Variables will usually need to be initialized before you get into the loop. This is especially true of while loops since the boundary condition is at the top of the control structure.

    2. Loop boundary - You must construct a Boolean expression that becomes false when the problem is done. This is the most common source of error in coding a while loop. Be careful of off-by-one errors that cause the loop to happen one too few or one too many times.

    3. Contents of the loop - This is where the problem is solved. The statement of the loop must also provide the opportunity to reach the loop boundary. If there is no movement toward the loop boundary, you will get stuck in an infinite loop.

    4. State of variables after the loop - To ensure the correctness of your loop you must determine the status of key variables used in your loop. One way to do this is by tracing the code on paper.

  3. We now solve the problem by first developing pseudocode.

    Pseudocode:

    initialize total and count to 0
    initialize smallest to Integer.MAX_VALUE
    get first score
    while score is not a negative value
         increment total
         increment count
         change smallest if necessary
         get next score
    subtract smallest from total
    calculate average

  4. And now it is easy to develop a working loop from this concise and easy to read pseudocode.

  5. Tracing code is best done in a chart or table format. It keeps your data organized better than marking values all over the page. We now trace the following sample data input.

65 23 81 17 45 -1

score
score >= 0
total
count
smallest
undefined
undefined
0
0
INT_MAX
65
true
65
1
65
23
true
88
2
23
81
true
169
3
23
17
true
186
4
17
45
true
231
5
17
-1
false

When the loop is terminated, the three key variables (total, score, and smallest) contain the correct answers.

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.