Factorial concept in C Programming

Do you know what is factorial of any numbers? Factorial is nothing but the multification of natural numbers upto given number.
Natural numbers starts from 1 to infinity. So If we need to find the factorial of n number, then we simply multiply all numbers from 1 to n. It can be denoted by n! in mathematical term. 

In the C programming before we find the factorial of number we need to know what the factorial is which is mentioned above. For example if we need to find factorial of 5, the answer is 1*2*3*4*5= 120.

To write this program in C program we can use any loop control functions (while, do while or for loop). We all know that meaning of loop is repeated testing.

So we need to write a formula which multiplies 1, 2, 3....n  to find factorial of n. So loop formula technique is declaring a value equals to 1 and increasing it upto n in the loop. 

So the required C program is:

#include<stdio.h>
#include<conio.h>
Void main ()
{
int i, n, factorial=1;
 (// 1!=1 so factorial = 1 initialized as basic)

printf(" Enter value of n="); 
scanf("%d", &n);
for (i=1; i<=n; i++)
 {
factorial = factorial*i;
}
printf("The facorial of %d is, factorial);
getch();
}


This is the basic program to find factorial of n number.
If we put n=5, for the first time it begins the test with i=1 in the for loop, from 1<=5 upto 5<=5 while doing i++ and loop fails when i=6, i.e. 6<=5 is wrong. 

At the each loop testing from i=1 to i=5, the body of loop, Factorial=Factorial*i multiplies the initialied value of factorial =1 with i and stores new value of factorial.
It can be shown as following tracing(for n=5):
For i=1
Factorial = Factorial *i = 1*1 =1 (this value stores to factorial for next loop)
(Factorial = 1 was initialized or defined already)

For i=2
Factorial = 1*2 =2 

For i=3
Factorial = 2*3=6

For i=4
Factorial = 6*4= 24

For i=5
Factorial = 24*5 = 120

For i=6
6<=5 is wrong so loop stops here and prints 120.

This is how c program works to find factorial of given number.

Did you get it? Comment down.

Post a Comment

If you need anything to ask, Comment below:

Previous Post Next Post