Learn C++ · lesson 50 of 61 · about 8 minutes
Functions That Call Themselves
Solve a problem by solving a smaller copy of the same problem.
What you'll learn
- Write a base case that stops the recursion
- Write a recursive case that moves towards it
- Return values from recursive calls
Down the spiral stairs
After the armoury, the hero climbs into the tower and has to come back down the spiral stairs. The player types how many floors up the hero is, and the adventure says each one on the way down, Floor 3, Floor 2, Floor 1, then You reach the bottom of the tower. More than 9 floors is too long a climb. A loop could count the floors, but this unit is about another way: a function that calls itself. descend(3) says floor 3 and calls descend(2), and descend(0) is the bottom.
A function inside itself
A recursive function calls itself. Each call works on a smaller piece of the problem, until the piece is so small the answer is obvious.
Every recursive function needs two parts:
- A base case that returns without calling itself
- A recursive case that calls itself on something smaller
Counting down
#include <iostream>
void countdown(int n) {
if (n == 0) {
std::cout << "Lift off!\n";
return;
}
std::cout << n << "\n";
countdown(n - 1);
}
int main() {
countdown(3);
}Output
3
2
1
Lift off!Returning an answer
The factorial of 5 is 5 × 4 × 3 × 2 × 1, which is the same as 5 × (the factorial of 4). So factorial(n) can return n * factorial(n - 1), with factorial(1) returning 1.
Factorial
#include <iostream>
long long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
std::cout << factorial(5) << "\n";
std::cout << factorial(15) << "\n";
}Output
120
1307674368000A base case that catches the bottom
The stairs use if (floor <= 0) rather than if (floor == 0). Counting down from 3 lands on 0 either way, but a player who types 0 or a negative number would never land exactly on 0 with ==, and the calls would go on until the program crashed. <= 0 catches every number at the bottom, so the hero always arrives.
Tip
Each call must get closer to the base case. If it never gets there, the calls fill up the stack and the program crashes.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.