Recursion
A recursive function calls itself. It's a natural fit for problems that can be broken into smaller, identical subproblems.
Every recursive function needs a base case โ a condition that stops the recursion. Without it, you get infinite recursion and a stack overflow.
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
Each call adds a frame to the call stack. When the base case is reached, the stack unwinds and each frame returns its result to the caller.
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
Recursion can be elegant, but it uses memory. Iterative solutions are often more efficient. Use recursion when it makes the code simpler to understand.
Try it Yourself โ