C Recursion
Recursion is when a function calls itself. It sounds circular, but it is a natural way to solve problems that contain smaller copies of themselves: the sum of 1..n is n plus the sum of 1..n-1; a folder's size is its files plus the sizes of its sub-folders.
Every recursive function needs two parts:
- A base case that is answered directly, without another call — this is what stops the recursion.
- A recursive case that calls the function on a smaller version of the problem, moving closer to the base case.
A first example: summing numbers
#include <stdio.h>
int sum_to(int n) {
if (n == 0) { // base case
return 0;
}
return n + sum_to(n - 1); // recursive case
}
int main(void) {
printf("sum_to(5) = %d\n", sum_to(5));
printf("sum_to(100) = %d\n", sum_to(100));
return 0;
}sum_to(5) = 15
sum_to(100) = 5050
Here is how sum_to(3) unfolds. Each call waits for the one below it, then adds its own n:
sum_to(3) = 3 + sum_to(2)
= 2 + sum_to(1)
= 1 + sum_to(0)
= 0 <- base case
= 1 + 0 = 1
= 2 + 1 = 3
= 3 + 3 = 6Watching the calls
Adding output with an indentation level makes the "going down" and "coming back up" visible:
#include <stdio.h>
long factorial(int n, int depth) {
printf("%*scall factorial(%d)\n", depth * 2, "", n);
long result;
if (n <= 1) {
result = 1;
} else {
result = n * factorial(n - 1, depth + 1);
}
printf("%*sreturn %ld\n", depth * 2, "", result);
return result;
}
int main(void) {
printf("4! = %ld\n", factorial(4, 0));
return 0;
}call factorial(4)
call factorial(3)
call factorial(2)
call factorial(1)
return 1
return 2
return 6
return 24
4! = 24
(%*s with an empty string prints depth * 2 spaces — a neat trick for indentation.)
Each call gets its own copy of n and result, stored in a separate stack frame. That is why the values do not overwrite each other.
Recursion on arrays and strings
Recursion works well with data that can be split into "first element + the rest":
#include <stdio.h>
int array_max(const int *a, int n) {
if (n == 1) {
return a[0];
}
int rest_max = array_max(a + 1, n - 1);
return a[0] > rest_max ? a[0] : rest_max;
}
void print_reversed(const char *s) {
if (*s == '\0') {
return;
}
print_reversed(s + 1); // first print the rest...
putchar(*s); // ...then this character
}
int main(void) {
int data[] = {14, 3, 27, 9, 21};
printf("max = %d\n", array_max(data, 5));
print_reversed("recursion");
putchar('\n');
return 0;
}max = 27
noisrucer
Classic recursive algorithms
Some problems are much easier to express recursively. The greatest common divisor (Euclid's algorithm) and powers by repeated squaring are two examples:
#include <stdio.h>
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
long long power(long long base, int exp) {
if (exp == 0) return 1;
long long half = power(base, exp / 2);
return exp % 2 == 0 ? half * half : half * half * base;
}
int main(void) {
printf("gcd(84, 36) = %d\n", gcd(84, 36));
printf("gcd(17, 5) = %d\n", gcd(17, 5));
printf("3^13 = %lld\n", power(3, 13));
printf("2^40 = %lld\n", power(2, 40));
return 0;
}gcd(84, 36) = 12
gcd(17, 5) = 1
3^13 = 1594323
2^40 = 1099511627776
power needs only about log₂(exp) calls, because it halves the exponent each time.
Dangers: missing base cases and deep recursion
If the base case is missing or never reached, the function calls itself until the program runs out of stack memory and crashes with a stack overflow:
int forever(int n) {
return forever(n + 1); // no base case: crashes eventually
}Even correct recursion can be too deep: summing 1..10,000,000 recursively would need ten million stack frames. Some recursive solutions are also wildly inefficient — the naive Fibonacci function fib(n) = fib(n-1) + fib(n-2) recomputes the same values exponentially many times.
Recursion vs. loops
| Recursion | Loop | |
|---|---|---|
| Natural for | trees, nested structures, divide and conquer | simple repetition, counting |
| Memory | one stack frame per call | constant |
| Risk | stack overflow if too deep | infinite loop |
| Readability | often very elegant for recursive data | usually clearer for linear tasks |
Any recursive function can be rewritten with a loop (sometimes with an explicit stack). In C, prefer loops for simple linear tasks and use recursion where it clearly simplifies the code.
Tip: When writing a recursive function, write the base case first, then make sure every recursive call moves strictly towards it.
Test yourself
What is the purpose of the base case in a recursive function?
- To make the function faster
- To stop the recursion
- To call the function again
- To declare variables
Given int f(int n) { return n <= 1 ? 1 : n * f(n - 2); }, what is f(5)?
- 15
- 120
- 10
- 5
What happens if a recursive function never reaches its base case?
- It returns 0
- It loops quietly forever with no harm
- It eventually runs out of stack memory and crashes
- The compiler refuses to compile it