
Think together · Start with a little story
A girl wants to count a stack of cards. If she takes one away, what remains is still a stack of cards. Could she pass the same kind of question to herself again?
Lay out the process
- Count 3 cards1 plus the count of 2
- Count 2 cards1 plus the count of 1
- Count 0 cardsReturn 0
- Return step by step1, 2, 3
Recursion solves a smaller problem of the same kind, then brings the result back.
Each call has its own task; all the calls do not share one counter. You must know when to stop splitting the problem.
See both the calls and the returns
The task cards go from the bottom of the stack on the left to the top on the right. The rightmost card is the call currently running.
This call must compute 3 × f(2), so it waits for f(2).
This call must compute 2 × f(1), so it adds another call.
f(0) returns 1 directly, without adding another call.
Compute 1 × 1, get 1, and return.
Compute 2 × 1, get 2, and return.
Compute 3 × 2, get 6. This call is complete.
01What is recursion?
Recursion is a way to solve a problem:
Turn it into a smaller problem with the same structure, keep reducing it, and stop when you reach a case you can solve directly.
02What two parts does recursive code usually have?
Base case
When can you get the answer directly without making another call?
Recursive case
How do you make the current problem smaller and pass it to the next call?
03A tiny recursive example
void printDown(int n) {
if (n == 0) {
return;
}
std::cout << n << '\n';
printDown(n - 1);
}
Here:
n == 0is the base case.printDown(n - 1)is the recursive call.
04Why does n - 1 matter?
It makes the problem smaller step by step:
Eventually, the call reaches the base case.
05Is recursion just “calling yourself”?
That is not quite enough.
If a function only “calls itself” without making the problem smaller and reaching a base case, it is just an endless chain of calls—not a correct recursive algorithm.
06Is recursion always better than a loop?
No.
Some problems are simpler with loops. Others naturally fit recursion, such as trees, divide and conquer, and backtracking.
What have you learned?
- Recursion turns a problem into a smaller problem of the same kind.
- Recursive code usually has a base case and a recursive case.
- The problem size must keep moving toward the base case.
- A function calling itself is not enough to make a correct recursive algorithm.
- Recursion is not always better than a loop; it depends on the problem's structure.
Next: Why Does Recursion Need a Stopping Condition?
Your turn to try
When counting cards, if each recursive call still receives 3 instead of 2, does the process get closer to ending?
Ready? Open to see the explanation
No. The argument is not moving toward the stopping condition, so calls keep piling up and may eventually exhaust the call stack.