0

C program to print factorial.

#include<conio.h>
#include<stdio.h>
void main()
{
int a,f=1,i;
clrscr();
printf("Enter any number:");
scanf("%d",&a);
printf("Factorial of the given number is:");
for(i=a;i>0;i--)
{
 f=f*i;
}
printf("%d",f);
getch();
}

let’s start explainaton of the code first of all we need to understand what is factorial of a number. factorial of a number is the multiplication of all the positive no. less than or equal to it for example factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.

so lets look at the code here first of all we will take input from user of which no. you want factorial. Then the main logic starts from the for loop. here the no. i will starts from the no. a (no. of which we want factorial) and decrements till 1 Then the statement f = f*i; will store the value of factorial in f.

lets look how the f=f*i works so when i starts it is i = 5(assuming we are calculating factorial of 5) and f = 1 initially so the equation is f = 1 * 5 i.e f = 5 in 1st iteration. then the second iteration take place so i = 4 that means equation is f = 5*4 i.e f = 20. so this will take some more iterations to find the factorial of the no.

ks007

Leave a Reply

Your email address will not be published. Required fields are marked *