C Program to Find Factorial of a Number

Write a C Program to find factorial of a number?

This C Program prints the factorial of a given number.
Let’s discuss first, what is a factorial number.
In simple language, a factorial number is the product of all the number from 1 to the user-specified number.
n! = n * (n-1) * (n -2) * …….* 1
For example, Factorial of 4 is represented as
4! = 4 * 3 * 2 * 1 = 24

Here is the Programming code to find factorial of a number:

#include<stdio.h>
int fact(int num)
{
int i,a=1;
for(i=1;i<=num;i++)
{
a=a*i;
}
return(a);
}
int main()
{
int x,y;
printf(“enter the value of x”);
scanf(“%d”,&x);
y=fact(x);
printf(“y=%d”,y);
return 0;
}

Let’s try to understand the logic behind calculation part of this program.

We initialized the integer i value to 1 and also (i <= Number) condition will help the loop to terminate when the condition fails.

Let assume the user entered the integer is 3

  • First Iteration
    i = 1, Factorial = 1 and Number = 3, It means (i <= Number) the condition is true.

Factorial = Factorial * i;
Factorial = 1 *1 = 1
i++ means i will become 2

  • Second Iteration
    i = 2, Factorial = 1 and Number = 3 – It means (i <= Number) the condition is true

Factorial = Factorial * i;
Factorial = 1 *2 = 2
i++ means i will become 3

  • Third Iteration
    i = 3, Factorial = 2 and Number = 3 – It means (i <= Number) the condition is True

Factorial = Factorial * i;
Factorial = 2 *3 = 6
i++ means i will become 4 – It means (i <= Number) the condition is Flase. So, For loop will be Terminated.

Result:

Factorial of 3 = 6

All the best