Recursion
A function that calls itself, and the base case that makes it stop.
Introduction
In Iteració you learned to repeat a block as many times as needed.
With a while you can draw any polygon, any rosette and any spiral.
But there are figures that are not a repetition.
Look at a tree.
A tree is not a trunk repeated thirty times. It’s a trunk that opens into two branches, and each branch is a smaller tree.
This sentence —a branch is a smaller tree— you can’t write it with a loop.
You can write it with a function that calls itself.
A function that calls itself
Start with something you already know how to do.
In Iteració you drew the spiral with a while and an accumulator:
= 5
+= 5Now write it without a loop.
One segment of the spiral is one segment, and then a smaller spiral:
Read the last line carefully.
spiral calls spiral. The function uses itself, and this is called recursion.
The base case
Run this program and it won’t draw anything:
Keep reading — it's free.
The rest of this page is open to anyone with a free account. Nothing is sold here and nothing is charged for: the account exists so we know who agreed to the terms, and so we can send you the newsletter if you want it.
Create a free accountYou will be asked to accept the Terms · Privacy Policy