Problem
Statement
In
this program we will code a basic program to find the factorial of a number in
C programming language.
We
can do this with the help of
1. Looping Concept
Code
#include
int factorial(int n)
{
int fact=1;
for(int
i=1;i<=n;i++)
{
fact=fact*i;
}
return fact;
}
int main()
{
int n;
printf("Enter
the number?");
scanf("%d",&n);
int
res=factorial(n);
printf("Factorial of %d is : %d",n,res);
return 0;
}
Output
Enter
the number ? - 6
Factorial
of 6 is : 720
Explanation
Let us consider an example :
Suppose we have to find the factorial of 6,hence this means that we have to
calculate 1*2*3*4*5*6. It is clear that we can find the factorial of any number
'n',by multiplying each number from i:1 to 'n', such that fact=fact*i . This
can be achieved by using for loop from 1 to 'n'.
Note
: It is mandatory for you to initialize the result variable(here fact) with 1
as in an equation ' fact=fact*i ' , if fact=0 then overall result will be 0 as
well.


0 Comments