A factorial is the product of all the natural numbers less than or equal to the given number n. For Example, the factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720. In this article, we will explore a few programs to find the factorial of a number in C.

We can write the factorial program in C using two methods:
- Using Loops
- Using Recursion
1. Factorial Program using for Loop
In this method, we use a loop that runs (n – 1) times to get the product of all numbers starting from 1 to n. The below C program use for loop to find the factorial.
C
#include <stdio.h>
unsigned int factorial(unsigned int n)
{
int result = 1, i;
for (i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int main()
{
int num = 5;
printf ( "Factorial of %d is %d" , num, factorial(num));
return 0;
}
|
OutputFactorial of 5 is 120
Time Complexity: O(n)
Auxiliary Space: O(1)
2. Factorial Program using Recursion
In this method, we find the factorial in C using a recursive function. This recursive function will call itself n number of times and each time, the value of n will be decreased by 1. The recursion will stop when n = 1.
C
#include <stdio.h>
unsigned int factorial(unsigned int n)
{
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main()
{
int num = 5;
printf ( "Factorial of %d is %d" , num, factorial(num));
return 0;
}
|
OutputFactorial of 5 is 120
Time Complexity: O(n)
Auxiliary Space: O(n)
For more programs to find the factorial, refer to the article – Program for factorial of a number