Trying it out - Recursion: How to Grow a Tree

Objective

After completing this lesson, you will be able to apply the concepts of the previous lesson - Recursion: How to Grow a Tree.

Exercise

Your Turn!

Now it’s your turn. Download this document for a recap of the blocks we covered in this lesson and some hands-on exercises for you to explore.

What You Have Learned in This Lesson

Recursion

In this lesson, we advanced towards the topic of recursion. We speak of recursion when you use a custom block inside its own definition.

Recursive blocks go on forever, unless you specify a condition when they should stop or under which they should continue. Often that condition will be the "base case", i.e. the part of the algorithm that doesn’t need recursion.

Remember how we made the countdown block?

In its definition script we check whether the input number to count down from is greater than zero, otherwise we don’t let the block do anything, because we’re already done. In cases where the input is greater than zero, we let the sprite say that input for a second, and then we count down from the number that’s one below the current one:

The “countdown” block is used inside its own block definition – this is called “recursion”. The condition in the “if” block is called the base case of the recursion.

When a block definition only calls its own block once, the script accomplishes repetition, and we speak of "linear" recursion. This is cool, because it gives us the superpower to get by without ever having to use any of the loop blocks (forever, repeat, repeat until).

You can also use a custom block more than once inside its own definition. Then we speak of "exponential" or "branching" recursion, because instead of just a single repetition we get branches.

To visualize this, we made a block that draws a tree.

We used an input that we named "level" much in the same way that we counted down the start number in the first example, checking whether it is greater than zero, and stopping (not doing anything) once it is:

The tree block draws a branching tree which is generated through branching recursion with a block definition that calls the tree block twice inside its own definition.