Demystifying Recursion
Recursion is simply a function calling itself to solve a smaller piece of the same problem. Think of it like Russian Nesting Dolls: you keep opening smaller dolls until you find the tiny, solid one in the center (the Base Case). Then, you put them all back together!
Interactive Simulation: Factorial \( n! \)
def factorial(n):
if n == 1: # Base Case (Stop condition)
return 1
# Recursive Case (Call itself)
return n * factorial(n - 1)
int factorial(int n) {
if (n == 1) { // Base Case (Stop condition)
return 1;
}
// Recursive Case (Call itself)
return n * factorial(n - 1);
}
What is happening?
Step 1 / 10Click "Next Step" to begin.
Tip: You can use Left/Right arrow keys to navigate.
The Call Stack
Like a stack of plates: Newest calls go on top, and must finish first.
1. The Base Case (The Anchor)
Imagine asking someone a question, and they ask someone else, who asks someone else... it never ends!
The Base Case is the person who actually knows the answer and stops the chain. In code, it's an if statement that returns a real value instead of calling the function again.
2. Stack Overflow (The Crash)
The computer's memory (Call Stack) is like a physical table. You can only stack so many plates before they fall over. If you forget your Base Case, the computer keeps stacking function calls until it runs out of memory and crashes. This is a Stack Overflow!