How Recursion Works
Base cases and the call stack.
What Is Recursion?
Recursion is when a function calls itself to solve a problem. Each call works on a smaller piece of the original problem.
In C, any function can call itself, as long as there is a way for the calls to eventually stop.
The Base Case
Every recursive function needs a base case: a condition where it stops calling itself and returns directly.
Without a base case, the function would call itself forever and crash the program.
int countdown(int n) {
if (n == 0) return 0; /* base case */
return countdown(n - 1);
}All lessons in this course
- How Recursion Works
- Classic Recursive Problems
- Recursion vs Iteration
- Avoiding Stack Overflow