The Analogy: Asking the Person In Front of You in the Queue
You are standing in a long queue and want to know your position, but you cannot see the front. So you tap the shoulder of the person ahead and ask, "how many people are in front of you?" They do not know either, so they ask the person ahead of them. This continues until someone at the very front says "nobody" — zero. That answer travels back down the line, each person adding one before passing it on, until it reaches you.
Every recursive function has those same two parts. The person at the front who answers without asking anyone is the base case. Everyone else, who asks a smaller version of the same question and then adjusts the answer, is the recursive case. Miss the base case and the queue never ends; forget to ask a smaller question and you have an infinite loop with extra steps.
The unwinding matters as much as the descending. Each person in the queue is still standing there waiting while the question travels forward — and in C, each waiting caller occupies a stack frame with its own copy of the parameters and locals. Recursion is not free memory-wise, and that is the constraint that decides when to use it.
Syntax or Core Structure
#include <stdio.h>
unsigned long long factorial(unsigned n) {
if (n <= 1) return 1; /* base case: answer without asking */
return n * factorial(n - 1); /* recursive case: strictly smaller n */
}
int sum_digits(int n) {
if (n < 10) return n; /* base case: a single digit */
return n % 10 + sum_digits(n / 10);
}
int main(void) {
printf("5! = %llu\n", factorial(5));
printf("10! = %llu\n", factorial(10));
printf("digit sum of 9271 = %d\n", sum_digits(9271));
return 0;
}
Output:
5! = 120
10! = 3628800
digit sum of 9271 = 19
Both functions follow the identical shape: a guard that returns immediately, then a call on a strictly smaller input. In factorial the input shrinks by subtraction; in sum_digits it shrinks by integer division, which strips one digit per call. Either way, each call is measurably closer to the base case, which is the only thing that guarantees termination.
Tracing the descent and the return
factorial(4) does not compute anything on the way down. It builds up four pending multiplications, then resolves them on the way back:
| Depth | Call | Waiting on | Returns |
|---|---|---|---|
| 1 | factorial(4) | 4 * factorial(3) | 24 |
| 2 | factorial(3) | 3 * factorial(2) | 6 |
| 3 | factorial(2) | 2 * factorial(1) | 2 |
| 4 | factorial(1) | nothing (base case) | 1 |
Read the table downward to see the stack grow and upward to see the answers propagate. At depth 4 there are four live frames of factorial at once, each holding its own n.
Technical Depth: What Recursion Costs
Anything you can write recursively you can write with a loop, and vice versa. The choice is about which one expresses the problem more clearly, weighed against what the stack can afford.
| Recursion | Iteration | |
|---|---|---|
| Memory per step | one stack frame (parameters, locals, return address) | nothing extra |
| Depth limit | the stack, typically a few megabytes | none |
| Reads well for | branching data and divide-and-conquer | counting and linear scans |
| Failure mode | stack overflow, often a silent crash | a wrong bound, usually visible |
| Compiler help | none guaranteed | none needed |
Do not count on tail-call optimisation
sum_digits above ends by returning a call plus something, so it is not a tail call. But even when the recursive call is the last thing a function does, the C standard makes no promise that the compiler reuses the frame. GCC and Clang usually do at -O2 and usually do not at -O0. Never write C that requires the optimisation to avoid overflowing the stack — if you need unbounded depth, write a loop.
The trap of recomputation
The naive Fibonacci is the standard cautionary example:
long fib(int n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2); /* two calls, overlapping work */
}
Each call spawns two more, so the number of calls roughly multiplies as n grows rather than adding — the growth is exponential, around 1.6 to the power of n. fib(10) is instant, fib(40) takes seconds, and fib(50) will not finish while you watch. The problem is not recursion; it is that fib(38) gets computed millions of separate times. Give the function a cache and the same shape becomes linear:
/* The caller owns the cache, so there is no hidden state and no static. */
long fib_cached(int n, long *cache, int cache_len) {
if (n < 2) return n;
if (n >= cache_len) return -1; /* refuse rather than overrun */
if (cache[n] != 0) return cache[n]; /* already known */
cache[n] = fib_cached(n - 1, cache, cache_len)
+ fib_cached(n - 2, cache, cache_len);
return cache[n];
}
Called with long cache[64] = {0}; this computes each value once. That single line of memoisation is the difference between exponential and linear.
Mutual recursion
Functions can also call each other in a cycle. This needs a prototype, because the first one refers to a function defined later:
int is_odd(int n); /* prototype breaks the circularity */
int is_even(int n) { return n == 0 ? 1 : is_odd(n - 1); }
int is_odd(int n) { return n == 0 ? 0 : is_even(n - 1); }
It is a fine illustration and a terrible implementation — n % 2 == 0 does the same job in constant time and constant space. Mutual recursion earns its place when the data is mutually nested, as in an expression parser where a term contains factors that can contain whole parenthesised expressions.
Real World Example: Looking Up a Price in a Sorted Table
Product ids arrive sorted, and you need the row for a given id. Scanning every row works, but halving the search space on each step is what real lookup code does — and stated recursively, binary search reads almost exactly like its own definition: look at the middle; if it is not the answer, search the half that could still contain it.
#include <stdio.h>
/* Returns the index of target in a[lo..hi], or -1 if it is absent.
*probes counts how many midpoints we examined. */
int find_id(const int *a, int lo, int hi, int target, int *probes) {
if (lo > hi) return -1; /* base case: empty range */
int mid = lo + (hi - lo) / 2; /* no overflow, unlike (lo+hi)/2 */
(*probes)++;
if (a[mid] == target) return mid;
if (a[mid] < target) return find_id(a, mid + 1, hi, target, probes);
return find_id(a, lo, mid - 1, target, probes);
}
int main(void) {
const int ids[] = { 102, 118, 145, 203, 219, 240, 311, 400 };
const int n = (int)(sizeof ids / sizeof ids[0]);
int probes = 0;
int at = find_id(ids, 0, n - 1, 219, &probes);
printf("219: index %d (%d probes)\n", at, probes);
probes = 0;
at = find_id(ids, 0, n - 1, 250, &probes);
printf("250: index %d (%d probes)\n", at, probes);
return 0;
}
Output:
219: index 4 (3 probes)
250: index -1 (4 probes)
Follow the successful search: the range starts at 0..7, the midpoint is index 3 holding 203, which is too small, so the range becomes 4..7; the midpoint 5 holds 240, too big, so the range becomes 4..4; that midpoint is the answer. Three probes into eight rows. The failing search narrows the same way until lo passes hi, which is the base case that returns -1.
Two details in this code are the actual craft. lo + (hi - lo) / 2 instead of (lo + hi) / 2 because the second form can overflow int on large arrays. And the recursion depth is bounded by log base 2 of the row count — about 20 frames for a million rows, 30 for a billion — so unlike a recursion that descends once per element, this one can never exhaust the stack. That bound is what makes recursion the right call here rather than a risk.
Common Mistakes
- No base case. The function calls itself unconditionally and the program dies with a stack overflow, usually reported as a plain segmentation fault with no clue about which function was at fault.
- A base case that is never reached.
factorial(n)recursing onninstead ofn - 1, or onn + 1. There is a base case in the source; the arguments simply never arrive at it. Every recursive call must make measurable progress.
- Forgetting that negative input skips the guard.
if (n == 0) return 1;looks like a base case until someone passes -3. Use<=in the guard, or validate at the boundary.
- Recomputing the same subproblem. Naive Fibonacci and naive "count paths" style problems. If the recursion tree revisits inputs, add a cache.
- Using recursion for a plain linear scan. Summing an array recursively burns one frame per element and overflows the stack at a few hundred thousand items. A
forloop handles a billion.
- Large arrays as locals in a recursive function.
char buffer[8192];inside a function that recurses 500 deep is 4 MB of stack. Allocate once outside and pass a pointer in.
- A code path that returns nothing. Add an
if/else ifchain with no finalelseand one branch falls off the end, so the caller reads an indeterminate value.-Wallcatches it; heed the warning.
- Accumulating into a global instead of returning. The function then cannot be called twice without a reset, and a recursive call cannot be nested inside another use of the same function. Return the value, or pass an accumulator parameter.
Best Practices
- Write the base case first, before the recursive call. It forces you to answer "what is the smallest version of this problem?" while the design is still cheap to change.
- For every recursive call, state out loud which argument got smaller and why it cannot stall. If you cannot say it, the function does not terminate.
- Keep frames small. Parameters, a couple of scalars, no big local arrays. Depth multiplies whatever you put in there.
- Prefer recursion when the data branches — trees, nested expressions, divide-and-conquer — and a loop when the work is linear.
- Bound the depth explicitly when the input comes from outside your program. A
int depthparameter withif (depth > MAX_DEPTH) return -1;turns a crash on hostile input into a clean error.
- Add a cache the moment the recursion tree revisits the same input, and let the caller own the cache rather than hiding it in a
static.
- Test the boundaries explicitly: zero, one, the base case itself, and one step above it. Recursion bugs cluster at the edges, not in the middle.
- Prefer returning a value to mutating shared state. A recursive function that only reads its parameters and returns a result is one you can reason about one frame at a time.
Practice Exercises
- Trace before you run. Write
sum_digitsfrom this lesson and, on paper, produce the full call trace forsum_digits(9271)in the same four-column format used forfactorial(4)above — call, what it waits on, and what it returns. Then addprintfat the top and bottom of the function to print an indented enter/exit line, run it, and compare with your table.
- Recursive and iterative, side by side. Implement
reverse_stringtwice: once with a loop swapping the ends inward, and once recursively by swapping the outer two characters and recursing on the inside. Then answer in writing: at what input length does the recursive version become a bad idea, and what exactly goes wrong first?
- Measure the exponential. Add a global call counter to naive
fiband print it forn= 10, 20 and 25. Note roughly how the count multiplies asngrows by 5. Then implementfib_cachedwith a caller-owned array, print both the value and the call count forn= 25, and record the ratio between the two counts.
- Harden the binary search. Take
find_idand add adepthparameter that refuses to recurse past 40 levels. Then feed it a deliberately unsorted array and describe what it returns and why that is not a bug in the function. Finally rewrite it as awhileloop with the same signature minus the recursion, and say which version you would put into a codebase and why.