- 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.
-
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.
-
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.
-
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.
-
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.
-
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.
- 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
-
And now it is easy to develop a working loop from this concise and easy to read pseudocode.
- 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.