Page 73 - Introduction to Programming with Java: A Problem Solving Approach
P. 73
To check a loop’s terminal condition, temporarily change the terminal condition to
produce what you think will be exactly one iteration. For example, in this most recent
pseudocode version of the Happy birthday algorithm (where the initial count is zero),
change the final count from 100 to 1. Then ask yourself, “How many print operations
will occur?” In this case, the initial count is 0. The first time the condition is tested, the condition is “0 is less than 1,” which is true. So the condition is satisfied and the loop’s subordinate statements execute. Since the final statement in the loop increments the count to 1, the next time the condition is tested, the condition is “1 is less than 1,” which is false. So the condition is not satisfied, and looping terminates. Since using 1 in the loop condition produces one iteration, you can have confidence that using 100 in the loop condition will produce 100 iterations.
User Query Termination
To understand user query termination, consider an algorithm which repeatedly asks a user for numbers and calculates and prints the squares of the input values. This activity should continue as long as the user an- swers “y” to a “Continue?” prompt.
Figure 2.11 displays this algorithm as pseudocode. Within the while loop body, the first statement prompts the user to enter a number, the third statement does the computation, and the fourth statement prints the result. The query “Continue? (y/n)” and the corresponding input come just before the end of the body. This loop always executes at least one time, because we assign “y” to the continue variable before the loop begins.
2.9 LoopTerminationTechniques 39
Simplify the problem to check its essence.
set continue to “y”
Apago PDF Enhancer
while continue equals “y”
print “Enter a number: “
input num
set square to num * num
print num “ squared is ” square print “Continue? (y/n): ”
input continue
Figure 2.11 Print Squares algorithm that uses a query loop
Suppose that you want to give the user the opportunity to quit before entering even one number to
square. You can do that by replacing the first statement: set continue to “y”
with these two statements:
print “Do you want to print a square? (y/n): ”
input continue
This provides the user the option to enter “n” so that no squares will be computed.
Sentinel Value Termination
To understand sentinel value termination, consider an algorithm that reads in bowling scores repeatedly until a sentinel value of 1 is entered. Then, the algorithm prints the average score.