A recursive function requires a base condition that terminates the recursive calls. Without a reachable base condition, recursion can continue until the program exhausts its available stack space.
#include <stdio.h>
int factorial(int n)
{
if (n == 0)
{
return 1;
}
return n * factorial(n - 1);
}
int main(void)
{
int number = 5;
printf("Factorial of %d = %d\n",
number, factorial(number));
return 0;
}
Example Output #
Factorial of 5 = 120
Explanation #
The condition:
if (n == 0)
{
return 1;
}
is the base condition. When n reaches 0, the function returns 1 without making another recursive call.
The recursive step is:
return n * factorial(n - 1);
Each call decreases n by one, moving the computation toward the base condition.
Recursive Execution #
For factorial(5), the calls proceed as follows:
| Call | Action |
|---|---|
factorial(5) |
Returns 5 * factorial(4) |
factorial(4) |
Returns 4 * factorial(3) |
factorial(3) |
Returns 3 * factorial(2) |
factorial(2) |
Returns 2 * factorial(1) |
factorial(1) |
Returns 1 * factorial(0) |
factorial(0) |
Returns 1 — base condition |
As the calls return, the pending multiplications are evaluated:\[ 5 \times 4 \times 3 \times 2 \times 1 = 120 \]
Base Condition and Recursive Step #
| Component | Purpose |
|---|---|
| Base condition | Stops further recursive calls |
| Recursive step | Reduces the problem to a smaller instance |
| Progress toward the base condition | Ensures the recursion can terminate for valid inputs |
The function assumes a non-negative integer input. For negative values, the condition n == 0 is never reached through repeated decrements, so the function does not terminate normally. Input validation is necessary if values outside the intended range are possible.