Factorial Calculation Program in C & C++

In this tutorial I have shared the code for factorial calculation program. Although there are number of ways to code the factorial program but this one is very basic using the FOR Loop. The concept of factorial is very simple in mathematics, the formula is given below.

1! + 2! + 3! + 4! + 5!

1 + (2 * 1) + (3 * 2 * 1) + (4 * 3 * 2 * 1) + (5 * 4 * 3* 2 * 1)

In simple, the below mentioned formula is used for factorial of 5.

5 * 4 * 3* 2 * 1 =120

Now, we should come to the main agenda writing Program in C Language which calculate the factorial of number (1 to 5).

C Source Code

#include<stdio.h>

int main()
{

int fact= 1,i,j;

for (i = 1;i<=5;i++)
{

for (j=6 – i;j>=1;j–)
{
fact = j * fact;
}
printf("%d ",fact);
fact=1;
}
getch();
return 0;
}

C++ Source Code

#include<iostream.h>

int main()
{

int fact= 1,i,j;

for (i = 1;i<=5;i++)
{

for (j=6 – i;j>=1;j–)
{
fact = j * fact;
}
cout<<fact;
fact=1;
}
getch();
return 0;
}

This program will generate the following Output

Output

image

Be Sociable, Share!

Leave a Reply