Explain it simply
Explain it simply
Recursion is a function solving a smaller copy of its own problem by calling itself. Picture a dark cinema: to learn which row you are in, you ask the person in front of you, who asks the person in front of them, and so on. The person in the front row asks nobody and simply answers "1". That answer is the base case.
As the answer travels back, each person adds 1 and passes it to the person behind. For this to work, two rules must hold: every question must move one row closer to the front, and a front row must actually exist.
Problem → Why → Solution
The problem: one unexpected input crashes the program
sum(5) returns the correct 15, so the function seems finished. Later a value typed by the user is passed straight in, and sum(-1) gets called. The program never prints a result; it simply dies. Built with GCC at -O0 on Windows, it prints "start" and then exits with status 0xC00000FD (stack overflow) and no message at all.
#include <stdio.h>
int sum(int n) {
if (n == 0) { /* -1, -2, -3 ... never equals 0 */
return 0;
}
return n + sum(n - 1);
}
int main(void) {
printf("start\n");
printf("%d\n", sum(-1)); /* crashes: stack overflow */
return 0;
}Why does it crash?
Starting at -1, n moves away from 0 (-2, -3, ...), so the base case is never reached. Every call reserves a new frame on the stack, none of them ever returns, and the stack memory runs out. A base case must be reachable for every input the function accepts; here, if (n <= 0) is the fix.
Core concept: one frame per call, then the unwinding
Each time a recursive function is called, C creates a new frame on the stack holding that call's parameters and local variables. sum(3), sum(2) and sum(1) each have their own n, and they never interfere. In return n + sum(n - 1);, the addition has to wait until sum(n - 1) comes back, so the frames pile up one on top of another.
When the base case is reached, the first real value (0) comes back and the stack unwinds. Each waiting frame finishes its addition and hands the result to its caller: 1 + 0, then 2 + 1, then 3 + 3. A correct recursive function needs two things: a base case reachable from every accepted input, and recursive calls that genuinely shrink the problem (n - 1, the rest of a string, half of an array). A quick sanity test is to trace the smallest inputs by hand, such as sum(0) and sum(1), before trusting large ones.
The stack is limited. A main thread usually gets only a few megabytes: 8 MB is common on Linux, Windows programs built with MinGW reserve 2 MB, and MSVC builds 1 MB. That makes depth, the number of calls waiting at the same time, the number to watch. A recursion like sum(100000), a hundred thousand frames deep, can crash, while a binary search that halves its range needs only about 20 levels even for a million elements.
With optimisation on, some compilers turn a tail call into a loop, but the C standard does not guarantee it, so never depend on it. When depth grows in step with the input size, a loop is the safer design.
- Each call gets a new frame and new n
- The problem shrinks one step per call
- The base case answers directly
- Frames unwind and combine results
Depth is the number of frames waiting at once, and it must stay far below the stack limit.
General pattern
ReturnType solve(Problem p) {
if (is_small_enough(p)) { /* base case */
return direct_answer(p);
}
Problem smaller = shrink(p); /* must move towards the base */
return combine(p, solve(smaller));
}Check the base case first and answer it directly. Otherwise make the problem genuinely smaller, call yourself on it, and combine the returned result with the current piece.
Example: adding 1 to n recursively
sum(5) becomes 5 + sum(4), sum(4) becomes 4 + sum(3), and so on down to sum(0). Only after sum(0) returns 0 directly do the waiting additions complete in reverse, producing 15.
Call stack while sum(3) runs
----------------------------
main() waiting for sum(3)
sum(3) n=3 waiting: 3 + sum(2)
sum(2) n=2 waiting: 2 + sum(1)
sum(1) n=1 waiting: 1 + sum(0)
sum(0) n=0 base case, returns 0 <- deepest point
unwinding: sum(1) = 1 + 0 = 1
sum(2) = 2 + 1 = 3
sum(3) = 3 + 3 = 6 -> back in main()#include <stdio.h>
int sum(int n) {
if (n == 0) {
return 0;
}
return n + sum(n - 1);
}
int main() {
printf("%d", sum(5));
return 0;
}Code breakdown
- Signature
int sum(int n) {Every call receives its own copy of n; the n of sum(5) and the n of sum(4) live in two different frames.
- Base case test
if (n == 0) {The condition that stops the recursion. Testing it first means it is checked before any recursive call. If negative input can arrive, write n <= 0.
- Direct answer
return 0;The first value returned without any further call. The unwinding starts here.
- Recursive case
return n + sum(n - 1);n - 1 shrinks the problem by one step. The addition happens only after sum(n - 1) returns, so this frame waits on the stack until then.
- First call
printf("%d", sum(5));Starts the whole chain. At its deepest, six frames (sum(5) down to sum(0)) are waiting, and the result 15 is printed.
15Watching the call stack yourself
Pass the depth along as an extra parameter and indent by it, and you can print how the calls descend and how the returns climb back. printf's %*s takes its width from an argument and pads the empty string "" with that many spaces.
#include <stdio.h>
/* Same logic as sum(), plus a depth counter for indentation. */
int sum_traced(int n, int depth) {
printf("%*scall sum(%d)\n", depth * 2, "", n);
if (n == 0) {
printf("%*sbase case returns 0\n", depth * 2, "");
return 0;
}
int result = n + sum_traced(n - 1, depth + 1);
printf("%*ssum(%d) returns %d\n", depth * 2, "", n, result);
return result;
}
int main(void) {
sum_traced(3, 0);
return 0;
}The output shows four "call" lines indented deeper and deeper, then "base case returns 0", followed by "sum(1) returns 1", "sum(2) returns 3" and "sum(3) returns 6" stepping back out.
When recursion is the right tool
When a problem splits into smaller pieces (halves, subtrees, subfolders) and stays shallow, recursion makes the code very clear. The binary search below halves a sorted array on every call, so ten elements need a depth of about four.
#include <stdio.h>
/* Returns the index of target in sorted[low..high], or -1. */
int find(const int sorted[], int low, int high, int target) {
if (low > high) {
return -1; /* base case: empty range */
}
int mid = low + (high - low) / 2;
if (sorted[mid] == target) {
return mid; /* base case: found it */
}
if (target < sorted[mid]) {
return find(sorted, low, mid - 1, target);
}
return find(sorted, mid + 1, high, target);
}
int main(void) {
int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
int last = (int)(sizeof primes / sizeof primes[0]) - 1;
printf("17 is at index %d\n", find(primes, 0, last, 17));
printf("4 is at index %d\n", find(primes, 0, last, 4));
return 0;
}| Shape of the problem | Better fit |
|---|---|
| Trees, folders, nested data | Recursion (shallow depth) |
| Halving (binary search, merge sort) | Recursion (depth about log2 n) |
| Simple counting from 1 to n | A loop (depth would equal n) |
| Same subproblems recomputed | A loop or memoization |
In real projects
Where this shows up in real projects
Tools that walk a directory tree (calling themselves for each subfolder), JSON and XML parsers, the recursive descent parsers and expression evaluators inside compilers, and quicksort and merge sort all rely on recursion every day. The data itself is nested, so the shape of the code matches the shape of the data.
In production code, recursion becomes risky when untrusted input controls the depth. A JSON file nesting [[[[...]]]] thousands of levels deep can exhaust an unprotected parser's stack and crash a server, which is why many parsers enforce a maximum nesting depth. Algorithms that would recurse once per pixel, such as an image editor's flood fill, are usually written as a loop with an explicit stack so large images cannot overflow the call stack.
Common mistakes
Common mistakes
1. A base case some inputs never reach
if (n == 0) is never true once n is negative. Built at -O0 the program crashes with a stack overflow (typically "Segmentation fault" on Linux); at -O2, GCC can turn the recursion into a loop, and the program hangs instead of crashing. Write the base case as a range test such as n <= 0.
2. A recursive call that does not shrink the problem
Forgetting the - 1 in return n + sum(n); makes every call solve the identical problem, so the base case never arrives. For every recursive call, ask yourself how its argument moves closer to the base case.
3. Forgetting integer overflow
Computing factorials in an int is right up to 12! = 479001600, but 13! no longer fits in 32 bits. A GCC 16 build printed 1932053504 instead of 6227020800, and since signed overflow is undefined behaviour, nothing at all is guaranteed. unsigned long long holds results up to 20!, and you still need to limit the input.
4. Recomputing the same subproblems
Writing fib(n) = fib(n - 1) + fib(n - 2) directly makes 331,160,281 calls for fib(40), because values like fib(38) are recomputed over and over. A loop that keeps the previous two results needs only about 40 steps.
Best practices
Best practices
- Put the base case at the top of the function and prefer a range test such as <= over ==.
- For every recursive function, ask what the maximum depth is, and consider a loop when it grows with the input size.
- Test 0, 1, negative values and the largest value you accept.
Mini challenge
Mini challenge: three recursive functions
Write three recursive functions, each with a different base case and a different way of shrinking the problem, and try them in main().
- unsigned digit_sum(unsigned n) adds the digits (9045 gives 18), shrinking with n / 10
- unsigned long long power(unsigned long long base, unsigned exp) halves exp so the depth stays about log2(exp)
- void print_reverse(const char *s) prints the string backwards, with '\0' as the base case
- No for or while loops allowed
#include <stdio.h>
unsigned digit_sum(unsigned n) {
// TODO: base case for a single digit
// TODO: last digit + digit_sum of the remaining digits
return 0;
}
unsigned long long power(unsigned long long base, unsigned exp) {
// TODO: base case exp == 0
// TODO: compute power(base, exp / 2) once and reuse it
return 0;
}
void print_reverse(const char *s) {
// TODO: stop at the terminating '\0'
// TODO: print the rest first, then the current character
}
int main(void) {
// TODO: print digit_sum(9045), power(2, 10), power(3, 13)
// TODO: print "stack" in reverse
return 0;
}Expected: The program prints: digit_sum(9045) = 18 power(2, 10) = 1024 power(3, 13) = 1594323 reverse of "stack" = kcats
Show hint
In power(), call half = power(base, exp / 2) only once, then return half * half for an even exp and half * half * base for an odd one. In print_reverse(), placing putchar() after the recursive call prints during the unwinding, which reverses the order.
Show solution
#include <stdio.h>
/* 9045 -> 9 + 0 + 4 + 5 = 18 */
unsigned digit_sum(unsigned n) {
if (n < 10) {
return n;
}
return n % 10 + digit_sum(n / 10);
}
/* base^exp by halving exp: about log2(exp) calls deep */
unsigned long long power(unsigned long long base, unsigned exp) {
if (exp == 0) {
return 1;
}
unsigned long long half = power(base, exp / 2);
if (exp % 2 == 0) {
return half * half;
}
return half * half * base;
}
/* Prints s backwards: print the rest first, then this char. */
void print_reverse(const char *s) {
if (*s == '\0') {
return;
}
print_reverse(s + 1);
putchar(*s);
}
int main(void) {
printf("digit_sum(9045) = %u\n", digit_sum(9045));
printf("power(2, 10) = %llu\n", power(2, 10));
printf("power(3, 13) = %llu\n", power(3, 13));
printf("reverse of \"stack\" = ");
print_reverse("stack");
putchar('\n');
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Every recursive function needs a base case reachable from every input and calls that genuinely shrink the problem.
- Each call has its own stack frame, and results are combined in reverse order as the stack unwinds.
- The stack holds only a few megabytes, so prefer a loop when depth grows with the input size.
- Watch for integer overflow and repeated subproblems, and remember that C does not guarantee tail-call optimisation.
GNU C compiler diagnostics — GNU Project