Recursion in one sentence
Recursion is a technique in which a function solves a problem by calling itself on a smaller version of the same problem. In C, a function can call itself like any other function, as long as it also has a way to stop.
A factorial example in C
The factorial of a whole number n, written n!, is the product of the whole numbers from 1 to n. For instance, 4! is 4 × 3 × 2 × 1, which is 24. A recursive function can compute it directly:
#include <stdio.h>
int factorial(int n) {
if (n <= 1) { /* base case: stop calling */
return 1;
}
return n * factorial(n - 1); /* recursive case: a smaller problem */
}
int main(void) {
printf("%d\n", factorial(5)); /* prints 120 */
return 0;
}
The example uses only stdio.h and standard C, so it also compiles as C++.
How the calls unfold
Calling factorial(5) runs through a chain of calls:
- factorial(5) needs factorial(4), so it waits.
- factorial(4) needs factorial(3), so it waits, and so on.
- factorial(1) meets the base case and returns 1.
- Each waiting call then multiplies its own n by the answer it received.
Written out, the work is 5 × 4 × 3 × 2 × 1, which gives 120. The calls go down until they reach the base case, and then the results come back up.
Why the base case is needed
A recursive function has two parts. The base case returns a value without calling the function again. The recursive case calls the function on a smaller input. Without a base case, the calls never stop. Each call takes up stack space, so the program eventually runs out of room for them and crashes.
If the stopping rule still feels unclear, the question of what is a base case in recursion is worth a closer look. It is the rule that keeps every recursive function finite.
Does C support recursion?
Yes. A C function can call itself, and the function’s name is visible inside its own body, so the self call needs no separate declaration. A prototype is only needed when a function is called before its definition appears in the file.
Recursion or a loop?
The factorial example can also be written with a for loop, and the loop gives the same result. Recursion fits best when the problem splits into smaller copies of itself, such as walking a tree of folders. For a simple count like this one, a loop is usually easier to step through and debug.
Summary
Recursion is a function calling itself on a smaller problem until it reaches a base case. The factorial example shows the whole pattern in a few lines: check for the base case, return the answer for the simplest input, and combine that answer with the result of a smaller call.