About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Monday, September 2, 2013

C Program to find Factorial of Number without using function

#include<stdio.h>
#include<conio.h>
void main()
{
int i,number,factorial;
printf("Enter the number : ");
scanf("%d",&n);

factorial = 1;
for(i=1;i<=n;i++)
      factorial = factorial * i;

printf("Factorial of %d is %d",n,factorial );
getch();
}
Output :
Enter the number : 5
Factorial of 5 is 120

Explanation of Program :

Before Explaining the program let us see how factorial is calculated -
Factorial of 5 = 5!
               = 5 * 4!
               = 5 * 4  * 3!
               = 5 * 4  * 3 * 2!
               = 5 * 4  * 3 * 2 * 1!
               = 5 * 4  * 3 * 2 * 1 * 0!
               = 5 * 4  * 3 * 2 * 1 * 1
               = 120
Firstly accept the number whose factorial is to be found.
printf("nEnter the number : ");
scanf("%d",&n);
We have to iterate from 1 to (n-1) using for/while/do-while loop. In each iteration we are going to multiply the current iteration number and result.
for(i=1;i<=n;i++)
      factorial = factorial * i;

Some Precautions to be taken :

Precaution 1 : Initialize ‘factorial’ variable

factorial = 1;
before going inside loop we must initialize factorial variable to 1 since by default each c variable have garbage value. If we forgot to initialize variable then garbage value will be multiplied and you will get garbage value as output.

Precaution 2 : For loop must start with 1

Suppose by mistake we write following statement -
for(i=0;i<=n;i++)
      factorial = factorial * i;
then in the very first iteration we will get factorial = 0 and in all successive iteration we will get result as 0 since anything multiplied by Zero is Zero

Precaution 3 : Try to accept lower value to calculate factorial

We have 2 bytes to store the integer in Borland C++ compiler, so we can have maximum limit upto certain thousand. Whenever we try to accept value greater than 20 we will get factorial overflow.

No comments: