Write a program to display factorial of a number in C

Calculating a factorial of a number in C is very easy. The loop is required to calculate the factorial of any given number.

What is factorial of a number (in maths)?

Factorial of a given number is the multiplication of all number from 1 to that number. e.g. factorial of 5 is: 5*4*3*2*1=120

Factorial of a number in C

#include<stdio.h>
#include<conio.h>

void main()
{
int n,fact=1,i;
clrscr();

printf("Enter any number to display factorial");
scanf("%d",&n);

for(i=n;i>=1;i--)
{
fact=fact*i;
}
printf("Factorial of number is=%d",fact);
getch();
}

Output

Enter any number to display factorial 5
Factorial of number is=120

Enter any number to display factorial 3
Factorial of number is=6

Other program codes

Program Code Explanation (PCE)

We input a number in variable ‘n’ to calculate factorial of a number in C.
Execute a for loop from n value to 1 and multiply each value by ‘fact’ variable. We put 1 in ‘fact’ at the time of initialization. Then we multiply each value and store result in ‘fact’.

Finally, print the value of ‘fact’ variable. It is the factorial value of n.

Hope that you understand the above program code. If you find any doubt please comment me in below comment section.

You can also visit our tech blog zerootech.com

Leave a Comment

error: Don\'t make piracy - Write your own content :)