Sub topic 16
Recursion: base case and recursive case
This chapter assumes you can read C functions and know that each call gets its own stack frame holding its parameters and locals (see the call stack chapter). Later chapters cover tracing output, recursion patterns, and recurrences. Here the goal is to write and check the two parts every recursive function needs.
What recursion is
A function is recursive if it calls itself, directly or through another function. Every correct recursive function has two parts:
- The base case is an input small enough to answer directly, with no further call.
- The recursive case reduces the problem to a smaller instance of the same problem, calls the function on it, and uses the result to answer the original.
The recursive case relies on trust. Assume the call on the smaller input returns the right answer, then work out what to do with that answer.
#include <stdio.h>
unsigned long long fact(unsigned int n) {
if (n == 0) {
return 1; /* base case */
}
return n * fact(n - 1); /* recursive case */
}
int main(void) {
printf("%llu\n", fact(5));
printf("%llu\n", fact(20));
return 0;
}This prints 120 and 2432902008176640000. The definition mirrors the mathematics: 0! = 1 and n! = n × (n−1)!.
The three checks
Before you accept a recursive function, check three things.
- A base case exists. Some input returns without recursing.
- Every recursive call moves toward a base case. The argument must get strictly smaller under some measure, such as
ndecreasing, the remaining string shortening, or the list having fewer nodes. - The base case is actually reachable from every legal input. If the base case is
n == 0but a caller passes a negativeint, the argument moves away from 0 forever.
Failing check 1 or 2 gives infinite recursion. Each call adds a frame, the stack fills up, and the program crashes (typically a segmentation fault). The C standard does not define this behavior, so do not rely on any particular outcome.
Recursion on numbers
The digit sum of a non-negative integer shows a base case that is not zero. A one-digit number is its own digit sum, and for larger numbers you split off the last digit.
#include <stdio.h>
int digit_sum(int n) { /* requires n >= 0 */
if (n < 10) {
return n; /* base case */
}
return n % 10 + digit_sum(n / 10); /* smaller: n / 10 < n */
}
int main(void) {
printf("%d\n", digit_sum(9047));
return 0;
}The output is 20. For any n >= 10, n / 10 is smaller than n and non-negative, so the argument eventually drops below 10.
Choosing a different reduction can change the cost a lot. Computing b^e by repeated multiplication takes e calls. Halving the exponent takes about log₂ e calls.
#include <stdio.h>
long long power(long long b, unsigned int e) {
if (e == 0) {
return 1;
}
long long h = power(b, e / 2); /* one call, reused twice */
if (e % 2 == 0) {
return h * h;
}
return h * h * b;
}
int main(void) {
printf("%lld\n", power(3, 13));
return 0;
}This prints 1594323. The result is stored in h first. Writing power(b, e/2) * power(b, e/2) would make two calls per level and lose the speedup.
Recursion on pointers
The reduction does not have to be numeric. A string is empty or it is one character followed by a shorter string. Advancing the pointer shrinks the problem.
#include <stdio.h>
#include <stddef.h>
size_t rec_strlen(const char *s) {
if (*s == '\0') {
return 0; /* base case: empty string */
}
return 1 + rec_strlen(s + 1); /* the rest of the string is shorter */
}
int main(void) {
printf("%zu\n", rec_strlen("gate"));
return 0;
}The output is 4. Here the base case tests the null terminator, and s + 1 is pointer arithmetic that makes progress toward it.
Multiple base cases
Some functions need more than one base case, because the recursive case reaches back by more than one step. The Fibonacci recurrence uses fib(n-1) and fib(n-2), so both fib(0) and fib(1) must be answered directly. If you only handle n == 0, then fib(1) calls fib(-1), which never reaches the base case.
A safe rule: if the recursive case uses the input minus k, you need base cases for k consecutive smallest inputs.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| No base case | Stack overflow, crash | Add a test that returns without recursing |
| Argument does not shrink, for example `f(n)` or `f(n+1)` | Stack overflow | Recurse on `n - 1`, `n / 2`, or `s + 1` |
| Base case unreachable for some input, for example negative `n` with test `n == 0` | Stack overflow | Use `n <= 0`, or an unsigned parameter, or document the precondition |
| Missing `return` before the recursive call | Garbage result; using the value of a function that fell off its end is undefined behavior | Return the combined value on every path |
| Too few base cases | Recursion runs below the smallest valid input | Count how far back the recursive case reaches |
| Result overflows | Wrong value | Use a wider type; signed overflow is undefined, unsigned wraps |
Checking a function by hand
Test the smallest inputs and then one step beyond them. Take this function:
#include <stdio.h>
int g(int x) {
if (x == 0) {
return 0;
}
return x + g(x - 1);
}
int main(void) {
printf("%d\n", g(4));
return 0;
}g(0) is 0 by the base case. g(1) is 1 + g(0) = 1, and g(2) is 2 + 1 = 3. In general g(n) is n(n+1)/2, so g(4) prints 10. g(-1) would call g(-2), g(-3), and so on, failing check 3.
Exercise
The function int h(int n) { if (n == 1) return 1; return n * h(n - 1); } is called as h(0). What happens, and what single change makes the function safe for all n >= 0 and also gives 0! = 1?
Show answer
With n == 0 the base case is never reached, because the calls go h(-1), h(-2), and so on. The argument moves away from 1, the frames pile up, and the stack overflows, which crashes the program. Changing the test to if (n <= 1) return 1; handles n = 0 and n = 1, and every legal call now reaches the base case. (Negative inputs also return 1 with that test, so document that n must be non-negative, or make the parameter unsigned.)