Program to find Factorial of a Number in C
Before we write the program to find a factorial of a number in C language, let's understand how we can in general find factorial of a number and then we will write a program for it.
What is Factorial of a Number?
The factorial (denoted by n!
) for a number (say n
) is the product of all the numbers preceding n with the number itself.
!n = n * (n - 1) * (n - 2) * . . . * 2 * 1
For example,
!6 = 6 * 5 * 4 * 3 * 2 * 1 = 720
!12 = 12 * 11 * 10 * 9 * 8 * 7 * !6 = 479, 001, 600
We can say that,
!n = n * !(n - 1)
Important points-
Algorithm for Factorial Program:
Here are steps to be followed for the factorial program,
declare variables n and fact = 1 //n is the number whose factorial is to be calculated and fact is the variable in which we will store the result
read input from the user in n
initialize loop iterator i = 1 and run the loop till i <= n
do the following in each iteration of the loop
fact = fact * i
i++
print fact
Now let's see a few implementation of this program.
1. Program to find Factorial of a Number using for loop
In this program, we will use for loop to find factorial of a number.
#include<stdio.h>
void main()
{
int i, n;
long int fact = 1;
printf("Enter the number: ");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
fact = fact * i;
}
printf("Factorial of %d is %ld", n , fact);
}
Enter the number: 5
Factorial of 5 is 120
2. Program to find Factorial of a Number using while loop
In this program, we will use while loop to find factorial of a number.
#include<stdio.h>
void main()
{
int n;
long int fact = 1;
printf("Enter the number: ");
scanf("%d" , &n);
int i = n;
while(i) {
fact = fact * i;
i--;
}
printf("Factorial of %d is %ld", n , fact);
}
Enter the number: 0
Factorial of 0 is 1
Things to keep in mind while calculating factorial of a number-
-
The variable in which we will store our result should have a large size. int
can only store factorials upto 12. We use long
for higher numbers.
-
The variable in which we will store our result should always be initialized by 1. This is because if we don't initialize it, it will contain garbage value and the numbers will be multiplied with the garbage value. If we initialize it with 0, the product will always be zero.
-
We run the loop from 1 to n because we want the product of numbers from 1, 2, 3, ... to n.