Quick Answer
Recursion solves a problem with smaller calls to one function. It works in 3 steps. Step 1 goes down with smaller calls. Step 2 stops at the base case. Step 3 unwinds and builds the answer. Python stops at 1,000 nested calls by default. Memory cost is O(n) for factorial.
Recursion confuses beginners because a function that calls its own copy sounds like a trap. Will it stop? Where does the answer come from?
Recursion is a stack of paused work. Once you see that stack grow and shrink the idea clicks.
Sections below trace factorial(4) call by call. They also show the base case, tested Python and C++ code and the real memory cost.
What Is Recursion?
Recursion solves a problem by calling the same function on a smaller piece of that problem. Every call handles one small step and hands the rest to another copy of the same function.
Nesting boxes show the idea. Opening the biggest box means opening the one inside it.
You continue until the smallest box which is empty. That smallest box stops the chain.
Every recursion needs that stopping point. Without it the calls never end.
Recursion is two parts working together. One part shrinks the problem and one part stops the shrinking.
How Does Recursion Work Step by Step?
Computers track function calls with the call stack. Call stack is a pile of paused functions.
When a function calls another one the first pauses and the new call goes on top. Work always happens at the top of the pile.
Factorial of 4 shows the process. It multiplies every integer from 1 up to 4 so factorial(4) is 4 times 3 times 2 times 1 which equals 24.
Step #1: Go Down With Smaller Calls
What you get. Paused calls stacked in order. factorial(4) needs factorial(3) so factorial(3) goes on top. That repeats down to factorial(1).
Step #2: Stop at the Smallest Input
What you get. Direct answer with no further calls. factorial(1) returns 1 and the stack stops growing.
Step #3: Unwind and Build the Answer
What you get. Real answer built from the bottom. factorial(2) returns 2 then factorial(3) returns 6 and factorial(4) returns 24.
Output below comes from a traced Python version. Indent shows stack depth.
call factorial(4)
call factorial(3)
call factorial(2)
call factorial(1)
return 1
return 2 * 1 = 2
return 3 * 2 = 6
return 4 * 6 = 24
Four frames sit on the stack when factorial(1) returns. Going down solves nothing because every call only pauses. Math happens on the way back when a paused call uses the value that the call below it returned.
Watch a call tree grow on the Fibonacci visualiser.
What Are the Base Case and the Recursive Case?
Every recursive function has two parts. Missing one breaks it.
Base case is the stopping point. It is the smallest version of the problem and needs no more calls.
For factorial it is n of 1 or less which returns 1. Reaching it ends the growth of the stack and starts the unwinding.
Recursive case calls the function on a smaller input. For factorial it is n times factorial(n minus 1).
Every call must move closer to the stopping point. Otherwise the calls never stop and that bug is called infinite recursion.
How Do You Code Recursion in Python and C++?
Python version below maps the two parts onto four lines.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(4))
Lines 2 and 3 form the base case. Line 4 is the recursive case. No loop appears yet the function reaches every number from n down to 1.
C++ version below has the same shape. It returns a long long because factorials grow quickly.
#include <iostream>
using namespace std;
long long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
cout << factorial(4) << endl;
}
Use n <= 1 and not n == 1. Checking n == 1 alone never stops when n is 0.
Tested. Python 3.13.18 and g++ 13.3 with warnings on printed 24. Calling with n equal to 0 returned 1 and the n == 1 version raised RecursionError. Tests ran in a cloud sandbox.
What Is the Time and Space Cost of Recursion?
factorial(n) makes n calls so time is O(n). Loops have the same time. Space is where they differ.
Every waiting call takes a frame on the call stack. factorial(n) has n frames at its deepest point so space is O(n). Loops need one fixed amount of memory which is O(1).
| Version | Time | Space |
|---|---|---|
| Recursive factorial | O(n) | O(n) |
| Loop factorial | O(n) | O(1) |
See time complexity and Big O notation for the notation.
Stack space is not endless. Python raising the limit too high can crash the interpreter according to the sys module documentation.
Test below used a recursive sum function. sys.getrecursionlimit() returned 1000. Deepest n that worked was 998 and n of 5,000 raised RecursionError.
C++ has a stack limit too. On this machine with an 8 MB stack and no optimisation a recursive sum to 100,000 worked and a sum to 1,000,000 crashed with a segmentation fault. Same code built with -O2 handled 100,000,000 so build settings alter the result.
Is Recursion Faster Than Iteration?
No on the tested case. Recursion adds the cost of creating and removing frames. Test below computed factorial(900) 2,000 times with the best of 5 trials in CPython 3.13.18.
| Point | Recursion | Iteration |
|---|---|---|
| Time for 2,000 calls | 0.286 s | 0.198 s |
| Extra memory | O(n) frames | O(1) |
| Good for | Trees, graphs, divide and conquer | Counting and summing |
Branching problems fit recursion because the code matches the shape of the data. See merge sort and the N Queens problem for examples. Timings come from one cloud sandbox.
Frequently Asked Questions
What Is a Base Case in Recursion?
It is the condition that stops the calls. Simplest input that needs no further recursion is the answer like factorial(1) returning 1. Without it the calls never end.
Why Does Recursion Cause a Stack Overflow?
Every pending call takes a frame on the call stack. Deep recursion fills the stack and the process crashes. Missing stopping conditions are a common reason.
Does Recursion Beat a Loop on Speed?
No on the tested case. Recursive factorial took 0.286 s against 0.198 s for a loop. Frames cost time and memory.
Can Every Recursion Become a Loop?
Yes. Any recursive function can become iterative and sometimes needs your own stack. Choose the form that is clearer for the problem.
What Is Infinite Recursion?
It is recursion that never reaches the stopping point. Calls continue until the stack overflows. In the test a factorial with an n == 1 base case raised RecursionError for 0.
When Should You Use Recursion?
Use it for nested problems like trees, graphs and divide and conquer. Use a loop for plain counting or summing.
What Is the Recursion Limit in Python?
It is 1000 by default in the tested Python 3.13.18. Recursive sums failed above n of 998.
What Should You Remember About Recursion?
Recursion trusts a smaller copy of the function to do part of the work. Calls stack up on the way down and answers build on the way back. Base case is the safety net.
Key takeaways.
- Recursion needs two parts and the first is a stopping point.
- Memory cost is O(n) frames and Python stops near 1,000 calls.
- Loops beat recursion on the tested factorial.
Trace factorial(5) on paper. How many frames sit on the stack when factorial(1) returns?
Continue with the recursion lesson and the recursion practice set. Both stack data structure and dynamic programming build on the same idea.