A function that calls itself
After this: Follow a countdown and a factorial, name the base case and the recursive case, and say what happens without a base case.
On this page · 9 sections · 3 checks
Imagine you are standing in a long line of people, and you want to know your place in it. You cannot see the front. How can you find out without leaving the line?
You can ask the person in front of you. They do not know either, so they ask the person in front of them. The question moves forward, one person at a time, until it reaches someone who does know.
Here is a short line. Ana is first, then Ben, then Chen, then you.
- You ask Chen, "What is your place?" Chen does not know, so Chen asks Ben.
- Ben does not know, so Ben asks Ana.
- Nobody is in front of Ana, so she knows her answer: "I am number 1."
- Ben hears 1 and adds one: "I am number 2."
- Chen hears 2 and adds one: "I am number 3."
- You hear 3 and add one. You are number 4.
Two things made this work. First, everyone followed the same instruction: "If nobody is in front of me, I am number 1. If somebody is, I ask them and add one to their answer." Second, each person asked about a shorter line, so the questions had to end at the front.
This way of solving a problem is called . You solve a big problem by solving a smaller copy of the same problem, and you keep going until the copy is small enough to answer straight away. In code, a is a function that calls itself with a smaller input.
Why anyone wants this
Some jobs are made of smaller copies of themselves. A folder can hold files and other folders, and those folders can hold more folders. To count every file, you count the files in this folder, and then you do the same job for each folder inside it. You do not need to know how deep the folders go.
Recursion fits this kind of job well. You write the instruction for one level, and the same function deals with all the levels below. Later tutorials use it for trees and graphs, which have this same shape.
The smallest example: a countdown
Here is a function that counts down from a number and then prints liftoff. It is the simplest recursive function we can write.
def countdown(n): if n == 0: # base case: stop here print("liftoff") return print(n) # recursive case: one small piece of work... countdown(n - 1) # ...then the same job with a smaller number
countdown(3)3 2 1 liftoff
static void countdown(int n) { if (n == 0) { // base case: stop here System.out.println("liftoff"); return; } System.out.println(n); // recursive case: one small piece of work... countdown(n - 1); // ...then the same job with a smaller number}
countdown(3);3 2 1 liftoff
Here is what happens, one call at a time.
countdown(3)runs. 3 is not 0, so it prints 3 and callscountdown(2).countdown(2)prints 2 and callscountdown(1).countdown(1)prints 1 and callscountdown(0).countdown(0)finds thatnis 0. It prints liftoff and returns, and it makes no further call.- Each earlier call now has nothing left to do, so they finish one after another:
countdown(1), thencountdown(2), thencountdown(3).
Each call is a separate run of the same function, and each run has its own n.
The two parts
Think of the line of people again. Ana could answer straight away, and everyone else asked a smaller question. A recursive function has the same two parts, and it needs both of them.
The is an input the function can deal with straight away, without calling itself. In countdown it is the highlighted part: when n is 0, print liftoff and stop. In the line of people, it is Ana.
The is every other input. The function does one small piece of work and calls itself with a smaller input. In countdown, it prints n and then calls countdown(n - 1). In the line of people, it is asking the person in front.
Watch it happen
Press the button to run each step. Each box on the left is one call that has started and has not finished, and the top box is the one running. Watch the boxes pile up as the calls go down, then disappear once the base case has run.
The visualizer uses a few words that the next lesson explains. It calls each box a frame. It says a frame is pushed when a box is added, and popped when a box is removed.
- countdown(3)Call countdown(3). The calls go down 3, 2, 1, 0. The call for 0 is the base case, so it makes no smaller call.
- countdown(0)
- empty
- no calls yet
Call a function to push its first frame.
- calls
- 0
- depth
- 0
A function that gives back an answer
countdown only prints. Most recursive functions also give back an answer, in the way each person in the line passed back a number. The classic example is the factorial.
The factorial of a whole number is what you get when you multiply it by every smaller whole number, down to 1. Maths writes it with an exclamation mark, so 3! means "the factorial of 3". You say it as "three factorial".
| Written | Meaning | Value |
|---|---|---|
| 1! | 1 | 1 |
| 2! | 2 × 1 | 2 |
| 3! | 3 × 2 × 1 | 6 |
| 4! | 4 × 3 × 2 × 1 | 24 |
Now look at the row for 4!. After the first 4 comes 3 × 2 × 1, and that is 3!. So 4! is 4 × 3!. In the same way, 3! is 3 × 2!. A factorial is a number times a smaller factorial, which is a smaller copy of the same problem.
Where does it stop? Mathematicians define 0! as 1. This keeps the pattern working, because 1! is 1 × 0!, which is 1 × 1 = 1. So the base case is 0, and its answer is 1.
def factorial(n): if n == 0: # base case: the answer is known straight away return 1 return n * factorial(n - 1) # recursive case: a smaller call, then one multiplication
print(factorial(3))print(factorial(5))6 120
static int factorial(int n) { if (n == 0) return 1; // base case: the answer is known straight away return n * factorial(n - 1); // recursive case: a smaller call, then one multiplication}
System.out.println(factorial(3));System.out.println(factorial(5));6 120
The highlighted code is the base case. The line after it is the recursive case: it calls factorial with a smaller number, then multiplies the answer by n.
Here is factorial(3), one call at a time.
factorial(3)needsfactorial(2), so it calls it and waits.factorial(2)needsfactorial(1), so it calls it and waits.factorial(1)needsfactorial(0), so it calls it and waits.factorial(0)is the base case. It returns 1.factorial(1)receives 1 and returns 1 × 1 = 1.factorial(2)receives 1 and returns 2 × 1 = 2.factorial(3)receives 2 and returns 3 × 2 = 6.
The calls go down to the base case, and then the answers come back. This is the same as the question moving forward along the line, and the numbers coming back.
Watch it happen again
Run the same calls in the visualizer. This time each call has something to do when the smaller answer arrives.
- factorial(3)Call factorial(3). The calls go down 3, 2, 1, 0. Then the values come back: 1, 1, 2, 6.
- factorial(0)
- factorial(5)
- empty
- no calls yet
Call a function to push its first frame.
- calls
- 0
- depth
- 0
Without a base case
Remove the base case from factorial, and nothing ever gives an answer. factorial(3) asks for factorial(2), which asks for factorial(1), then 0, then −1, then −2, and so on. Every call waits for the next one, so no call can finish, and the program fails with an error.
def broken(n): return n * broken(n - 1) # nothing says stop: 3, 2, 1, 0, -1, -2, ...
print(broken(3))# RecursionError: maximum recursion depth exceededstatic int broken(int n) { return n * broken(n - 1); // nothing says stop: 3, 2, 1, 0, -1, -2, ...}
System.out.println(broken(3));// Exception in thread "main" java.lang.StackOverflowErrorCheck yourself
Why does factorial need the line if n == 0: return 1if (n == 0) return 1;?
Delete the base case from factorial and call factorial(3). What happens?
What does this print?
def mystery(n): if n == 0: return 0 return n + mystery(n - 1)
print(mystery(4))static int mystery(int n) { if (n == 0) return 0; return n + mystery(n - 1);}
System.out.println(mystery(4));Connect
- Say what recursion is: solving a problem by solving a smaller copy of the same problem.
- Name the two parts of a recursive function: a base case that needs no further call, and a recursive case that calls the function on a smaller input.
- Say what n! means, and follow factorial down to the base case and back.
- Check that each recursive call moves towards the base case.
- Say what happens without a base case: the calls never stop, and the program fails with RecursionError in Python or StackOverflowError in Java.