Sub topic 14
Recursion: Base Case and Recursive Case
Assume you know basic C syntax, functions, if statements, and how to compile and run a small program. Recursion is a technique in which a function calls itself to solve a smaller version of the same problem.
Every correct recursive function needs two parts:
- A base case is a condition that stops recursion and returns a direct answer.
- A recursive case calls the function again with an input closer to the base case.
The recursive call must make progress. If the input never moves toward the base case, the function keeps calling itself until the call stack overflows.
A simple example
The factorial of a nonnegative integer is:
0! = 1n! = n × (n - 1)!forn > 0
This definition maps directly to a recursive function:
#include <stdio.h>
int factorial(int n) {
if (n == 0) { /* base case */
return 1;
}
return n * factorial(n - 1); /* recursive case */
}
int main(void) {
printf("%d\n", factorial(4));
return 0;
}The output is:
24For factorial(4), the calls expand as follows:
factorial(4)
= 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * 2 * factorial(1)
= 4 * 3 * 2 * 1 * factorial(0)
= 4 * 3 * 2 * 1 * 1
= 24The calls are made until factorial(0) reaches the base case. Then the pending multiplications are evaluated as the calls return.
Common errors
A recursive function can fail in several ways:
- Missing base case: The function has no stopping condition.
- No progress: The recursive call uses the same argument, such as
factorial(n). - Wrong progress: The argument moves away from the base case.
- Missing return: A non-
voidfunction calls itself but does not return its result. - Invalid input: The factorial function above does not handle negative values. For negative input,
n - 1moves farther from zero.
A defensive version can reject negative input:
int factorial(int n) {
if (n < 0) {
return -1;
}
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}The call stack stores each active function call, including its parameter values and the location to return to. Recursive calls consume stack space, so very deep recursion can cause stack overflow even when the logic is correct.
Exercise
What does sum(3) return if int sum(int n) { if (n == 0) return 0; return n + sum(n - 1); }?
Show answer
It returns 6: 3 + 2 + 1 + 0.