C program to find factorial of a given number

C program to find factorial of a given number

This C program is to find factorial of a given number.

For eg factorial of 5!= 5*4*3*2*1   hence 5!=120

Logic

We just use a for loop and keep multiplying with each number(i++) till we reach till the number specified(n).

Dry Run of the Program

Take input ‘n’ for which you want to calculate it’s factorial for . Let us take n=4

1st iteration  for(i=1;i<=n;i++)  i.e   for(i=1;i<=4;i++) as n=4

fact=fact*i   i.e fact=1*1 as fact is initalized to 1 and i=1 hence fact=1

2nd iteration  for(i=2;i<=n;i++)  i.e   for(i=2;i<=4;i++)

fact=fact*i   i.e fact=1*2 hence fact=2

3rd iteration  for(i=3;i<=n;i++)  i.e   for(i=3;i<=4;i++)

fact=fact*i   i.e fact=2*3 hence fact=6

4th iteration  for(i=4;i<=n;i++)  i.e   for(i=4;i<=4;i++)

fact=fact*i   i.e fact=6*4 hence fact=24

For loop ends here

We print the output.

Program

#include<stdio.h>
void main()
{
	int i,n,fact=1;
 
  	printf("Enter a number to calculate it's factorial\n");
  	scanf("%d",&n);
 
	for(i=1;i<=n;i++)
	{
            fact=fact*i;
        }
	printf("Factorial of the num(%d) = %d\n",n,fact);
}

Output

Share Me!