Page 184 - Learn To Program With Scratch
P. 184
Ending a Computational Loop
NumberSearch Let’s say that we want to find the first power of 2 that is larger than 1,000.
2
1
3
.sb2 We’ll write a procedure that checks the numbers 2 , 2 , 2 , 2 , and so on, in
4
a loop. When we find the number we need, we want the program to say the
answer and stop the procedure. Figure 7-9 shows two ways to implement this
approach.
Call the FindAnswer
procedure. When it
returns, display the
result (which is saved
in the result variable).
Alternative
implementation
Figure 7-9: Two ways to find the first power of 2 that is larger than 1,000
The procedure on the left in Figure 7-9 initializes the result variable
to 2, which is the first power of 2 to be checked, and enters an infinite
loop in search for the answer. It checks the value of result in each itera-
tion of the loop. If result is greater than 1,000, the procedure invokes the
stop this script command to stop and return to the caller. Otherwise, the
command after the if block (which multiplies the previous value of result by
2) executes, and the next iteration of the loop begins. If you trace through
this procedure, you’ll see that the if block finds result to be 2 in the first
iteration, 4 in the second iteration, 8 in the third iteration, and so on. This
continues until result exceeds 1,000; at this point, the procedure stops and
returns to the caller, which displays the result using the say block.
Figure 7-9 (right) shows another way to implement the procedure.
Here, we used a repeat until block that continues to loop until result
becomes greater than 1,000. As in the first implementation, the loop
continues to double the value of result until it exceeds 1,000. When this
happens, the loop terminates naturally, and the procedure returns to the
caller. Note that we did not have to use the stop block in this case.
The stop block is also useful when you need to validate input from
users. You’ll see an example of this practical application next.
Validating User Input
When you write an application that reads some data from the user, you
should always check that the entered values are valid before starting to pro-
cess the data. Repetition structures can help you with this task. If the user’s
input is invalid, you can use a loop to display an appropriate error message
and ask the user to reenter the value.
162 Chapter 7
www.it-ebooks.info

