Goal: Make a tiny spider grow huge with recursion.
Vocabulary: size, if, > (greater than sign)
This procedure makes the spider's size grow by 10, over and over, until it reaches size 100. But instead of writing: setsize 10
, setsize 20
, setsize 30
... we write a procedure which keeps circling back to the beginning again. Every time it circles back, the spider's size is bigger, until it reaches a limit we set for it. Then the procedure stops.
- If size > 100 [stop] means: "If the size of the spider is greater than 100, stop the procedure." Every time the computer runs the grow procedure, it checks to see if the if command is true... Is the size greater than 100? If it is true, the procedure will stop without continuing with the commands below. If it is false, the procedure will keep running.
- Setsize size + 10 means, "Add 10 on to the spider's size." (If the spider's size was 10, now it will be 20. If it was 20, now it will be 30. And so on.)
- When we use grow as a command in the grow procedure, that tells the computer to start running the procedure all over again. A procedure which keeps circling back to the beginning by using its own name inside the procedure is called a recursive procedure. The computer will keep circling back to the beginning forever unless we tell it when to stop.
- You should always save your work before you test out a recursive procedure, in case it doesn't stop as you expect. Also, you can always interrupt a process by selecting "Stop All" from the pull-down Edit menu.
Try smaller numbers for changing the spider's size, such as setsize size + 3
Can you make the spider grow more slowly?
Can you take away the wait 1 command but keep the spider growing at the same speed?
Can you make the spider grow to a larger size?
Can you write a recursive procedure to make the spider shrink?
On Your Own - Project Ideas
Can you use recursion to make another creature grow or shrink?