On this page, you will learn how to stop recursion from going on forever.
It seemed to make sense to replace all the look-alike numbered tree scripts with a single recursive script with the same structure:
→
But it didn't work:
tree, level 9 size 50
, but look what happened. What's going wrong?
tree
, the sprite draws smaller and smaller left branches until it seems to be just spinning around in one place. It never turns right to finish the tree it's working on.
tree 1
block is different from the others; it just draws a line, no branches, and it puts the sprite back where it started.
tree 1
code and to the figure it draws.tree
block has to do something different at the lowest level!
This different version for the lowest level of a recursive script is called the base case.
tree
block from the bottom of the previous page so that it includes a base case to stop the script from calling itself forever.
On Unit 3 Lab 1 Page 3: Using Abstraction to Nest Triangles, you only drew the nested
triangle if size > 9. That is one way to stop the recursion from going on forever. Click here if you need a bigger hint.
tree
block. There are more. Use whatever makes most sense to you.tree, level: 9 size: 50
. If it is working properly, you should get a result like this.Recursive blocks call themselves. In order for them to finish, there must be some special case in which they don't call themselves. That is the base case, a simpler version of the block's script that doesn't call the block itself.
There is usually a conditional with two cases: a base case for the lowest level that stops the recursion from going on forever and a recursive case that calls the block itself at lower levels until it reaches the base case.
If a block keeps recursively calling itself forever (as when the sprite was just spinning around in one place), that's a bug, and we say the program is stuck in an infinite loop.
tree
script. Identify the base case and the recursive case, and discuss how recursion works in this script. tree
run in reasonable or unreasonable time? You could think this out, you could try timing the script for levels 8 through 12, or you could create a global count variable and add one to it first thing in the tree
block in order to record the number of times that the procedure is called for trees of different levels.