When learning programming, one of the most common beginner tasks is writing a factorial program in C. In this post, you’ll learn how to find the factorial of a number using recursion, one of the most important concepts in C programming.
What is a Factorial?
The factorial of a number n
is the product of all positive integers less than or equal to n
. It’s denoted as n!
.
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
Why Use Recursion?
Recursion is a technique where a function calls itself to solve a smaller part of the problem. It’s ideal for problems that can be broken into similar subproblems, like factorials.
Factorial Program in C Using Recursion
Here’s a simple and clear C program using recursion to find the factorial of a number:
#include <stdio.h>
// Recursive function to find factorial
int factorial(int n) {
if (n == 0 || n == 1)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive call
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0)
printf("Factorial is not defined for negative numbers.\n");
else
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Explanation
- If
n
is 0 or 1, the factorial is 1 (base case). - Otherwise, the function calls itself with
n-1
and multiplies it byn
. - This continues until it reaches the base case.
Sample Output
Enter a number: 5
Factorial of 5 is 120
When to Use Recursion for Factorials?
Use recursion:
- For educational or demonstration purposes
- When writing short, elegant code
Avoid recursion:
- When performance is critical (use iteration instead to avoid stack overflow for large numbers)
Final Thoughts
The factorial program in C using recursion is an excellent example to understand how recursive functions work. It’s also a key building block for learning advanced topics like backtracking, divide-and-conquer, and data structures.