Recursion
Prerequisites: Bit manipulation
A recursive function calls itself with a smaller version of the same problem, until it reaches a base case that stops the recursion.
int factorial(int n) {
if (n <= 1) {
return 1; // base case
}
return n * factorial(n - 1); // recursive case
}
printf("%d\n", factorial(5)); // 120
Each call adds a new frame to the call stack; too many nested calls with no base case in sight (or one that's never reached) exhausts the stack, crashing with a stack overflow.
Common mistakes
- Forgetting the base case entirely, or writing one that's unreachable for some inputs — both lead to infinite recursion.