C Program for Factorial Using Recursion
int factorial(int n) { if (n == 0) return 1; else return n * factorial(n - 1); } and calls it from main() to compute the factorial of a given number.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int factorial(int n) { if (n == 0) return 1; else return n * factorial(n - 1); } int main() { int num = 5; printf("Factorial of %d is %d\n", num, factorial(num)); return 0; }
Dry Run
Let's trace factorial(5) through the code
Call factorial(5)
Since 5 != 0, return 5 * factorial(4)
Call factorial(4)
Since 4 != 0, return 4 * factorial(3)
Call factorial(3)
Since 3 != 0, return 3 * factorial(2)
Call factorial(2)
Since 2 != 0, return 2 * factorial(1)
Call factorial(1)
Since 1 != 0, return 1 * factorial(0)
Call factorial(0)
Since 0 == 0, return 1
Return values back up
factorial(1) = 1 * 1 = 1 factorial(2) = 2 * 1 = 2 factorial(3) = 3 * 2 = 6 factorial(4) = 4 * 6 = 24 factorial(5) = 5 * 24 = 120
| Function Call | Return Value |
|---|---|
| factorial(0) | 1 |
| factorial(1) | 1 |
| factorial(2) | 2 |
| factorial(3) | 6 |
| factorial(4) | 24 |
| factorial(5) | 120 |
Why This Works
Step 1: Base Case
The function stops calling itself when n == 0 and returns 1, which is the factorial of zero.
Step 2: Recursive Call
For any other number, the function calls itself with n - 1 to break the problem into smaller parts.
Step 3: Multiplying Results
Each call multiplies the current number n by the factorial of n - 1, building up the final result.
Alternative Approaches
#include <stdio.h> int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } int main() { int num = 5; printf("Factorial of %d is %d\n", num, factorial(num)); return 0; }
#include <stdio.h> int factorial_helper(int n, int acc) { if (n == 0) return acc; return factorial_helper(n - 1, n * acc); } int factorial(int n) { return factorial_helper(n, 1); } int main() { int num = 5; printf("Factorial of %d is %d\n", num, factorial(num)); return 0; }
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself n times, so the time grows linearly with the input number.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used is proportional to n.
Which Approach is Fastest?
The iterative approach uses constant space and is generally faster, while recursion is easier to read but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Simple code, small inputs |
| Iterative | O(n) | O(1) | Large inputs, performance |
| Tail Recursion | O(n) | O(n) or O(1) if optimized | Compiler-optimized recursion |