A recursive function is a function that calls itself to solve a problem by reducing it to smaller instances of the same problem. Each recursive call creates a new function invocation with its own parameter values and local variables.
#include <stdio.h>
int factorial(int n)
{
if (n <= 1)
{
return 1;
}
return n * factorial(n - 1);
}
int main(void)
{
int result = factorial(5);
printf("Factorial = %d\n", result);
return 0;
}
Example Output #
Factorial = 120
Explanation #
The function factorial() calls itself with a smaller argument:
return n * factorial(n - 1);
For factorial(5), the calls continue with decreasing values until the condition n <= 1 becomes true.
The recursive calculation is:\[ 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \]
Recursive Call Sequence #
| Function call | Operation |
|---|---|
factorial(5) |
5 * factorial(4) |
factorial(4) |
4 * factorial(3) |
factorial(3) |
3 * factorial(2) |
factorial(2) |
2 * factorial(1) |
factorial(1) |
Returns 1 |
As the calls return, their results are combined to produce 120.
Recursive functions are useful for problems with naturally recursive structures, such as tree traversal and divide-and-conquer algorithms. However, deep recursion can consume substantial stack space. The input must also be constrained to avoid integer overflow in the factorial calculation.