We have seen many ways of instructing the computer to do variations on the same thing over and over. The REPEAT command performs a set of instructions exactly for a given number of times. We've used recursion to repeat more complicated sets of instructions until some condition is met. The FOR command was similar to REPEAT, but let us use instructions that depended on how many times the command had been repeated. In this exercise we will learn the WHILE command. The WHILE command is used to repeat instructions until some condition is met, and a WHILE command is often easier to use and understand than recursion.
The syntax of the WHILE command is:
WHILE [true/false statement] [instruction list]
When presented with a WHILE statement, the computer first evaluates the true/false statement and then if that is true it executes the instruction list. When done with the instruction list, the computer returns to check the true/false statement again. (If you don't want the computer to get caught in an infinite loop, you'd better make sure that the actions in the instruction list eventually lead to the true/false statement being false!)
Here's an example:
TO COUNTTO :N MAKE "X 0 WHILE [:X < :N] [MAKE "X (:X + 1) PRINT :X] ENDIn the example, a counter variable :X is created. Each time the computer runs the instruction list given to the WHILE command, the value of :X increases by one. Since :N is never changed, the test :X < :N will eventually return the value false and the program will end.
Can you modify this program to count down from :N to 1?
Pages 208-211 of the text contain a discussion of Stella's modification of the FORWARD command to wrap inside a smaller region of the screen. The example below uses WHILE to do something similar. Before typing the procedure into your computer, read it and try to guess what it will do.
TO NFORWARD :DISTANCE
WHILE [:DISTANCE > 0] ; Repeat until we've gone far enough ~
[
IF (OR (XCOR>40) (XCOR<-40)) ; Draw only in a vertical strip ~
[
PENUP SETX (-1 * XCOR) PENDOWN
]
FORWARD 1 ; Move forward
MAKE "DISTANCE :DISTANCE - 1 ; Decrease distance counter
]
END
Test this by moving using commands like NFORWARD 60 with
different initial turtle headings and positions. Once you understand
the procedure definition and can predict how the NFORWARD
command will behave, see what happens when you replace
FORWARD with NFORWARD in your favorite drawing
commands. For example, try REPEAT 5 [RIGHT 144 NFORWARD
100].This program isn't perfect; what happens if the turtle starts with XCOR greater than 40? Why? Would you change this, and if so how?
Can you write a procedure which restricts the turtle's position to a circular region of the screen?