Page 72 - Introduction to Programming with Java: A Problem Solving Approach
P. 72
38 Chapter 2 Algorithms and Design Here’s how the while loop works:
• If the condition is true, execute all of the loop’s subordinate statements, and then jump back to the loop’s condition.
• Whentheloop’sconditionfinallybecomesfalse,jumptobelowtheloop,thatis,thefirststatementafter the loop’s last subordinate statement, and continue execution there.
2.9 Loop Termination Techniques
In this section we describe three common ways to terminate loops:
• Counter
Use a counter variable to keep track of the number of iterations.
• User query
Ask the user if he/she wants to continue. If the user responds yes, then execute the body of the loop. After each pass through the subordinate statements in the loop, ask the user again if he/she wants to continue.
• Sentinel value
is outside the normal range of input, and use it to indicate that looping should terminate. For example, if the normal range of input is positive numbers, the sentinel value could be a negative number like 21. Here’s how you do it: Continue to read in values and execute the loop until the entered value equals the sentinel value, and then stop the looping. In the real world, a sentinel is a guard who lets people continue to pass until the enemy arrives. So a program’s sentinel value is like a human sentinel—it allows the loop to continue or not.
Counter Termination
Figure 2.10’s Happy birthday algorithm is a good example of using a counter to terminate a looping opera- tion. We should point out, however, that the normal place for a computer to start counting is 0, rather than one. If we use the standard start-at-zero convention, Figure 2.10’s pseudocode changes to this:
set count to 0
while count is less than 100
print “Happy birthday!” set count to count 1
Notice that as we change the initial count value from 1 to 0, we also change condition comparison from “less than or equal to” to “less than.” This will produce the same 100 iterations, but this time, the count val- ues will be 0, 1, 2, ...98, 99. Each time you create a counter loop, it’s important to assure yourself that the number of iterations will be exactly what you want. Because you can start with numbers different than one, and because the termination condition can employ different comparison operators, it’s sometimes hard to be sure about the total number of iterations you’ll get. Here’s a handy trick to give you more confidence:
When a loop includes a data-input statement, identify a special value (a sentinel value) that Apago PDF Enhancer