 Home >>Cpp Programs >Factorial program in C++

# Factorial program in C++

### Factorial program in C++

The product of an integer and all the integers that lies below it is known as the factorial. The Factorial program in C++ is basically a program that is used to display the factorial of an integer that is entered by the user as an input. Please note that the factorial of N is denoted by the N!.

Let's derive the factorial of 5 then it will be:

`5! = 5*4*3*2*1 = 120`

The most widely use of the factorial generally lies in combination and permutations in mathematics.

### Different Ways through which the factorial program in C++ language can be written

There are numerous ways through which one can write the factorial program in C++ language. Here are the two most commonly used ways to write the factorial program as depicted below:

• Factorial Program using loop
• Factorial Program using recursion

### 1. Factorial Program using Loop

Here is the example

```#include <iostream>
using namespace std;
int main()
{
int i,f=1,num;
cout<<"Please Enter any Number to print factorial : ";
cin>>num;
for(i=1;i<=num;i++)
{
f=f*i;
}
cout<<"Here is the Factorial of " <<num<<"  "<<f<<endl;
return 0;
}
```
Output :
Please Enter any Number to print factorial : 6
Here is the Factorial of 6 720

### 2. Factorial Program using Recursion

Here is the example

```#include<iostream>
using namespace std;
int main()
{
int fact(int);
int f,num;
cout<<"Enter Your number to print Factorial ";
cin>>num;
f=fact(num);
cout<<"Here is the Factorial of given number : "<<f<<endl;
return 0;
}
int fact(int n)
{
if(n<0)
{
return(-1); /*if number is less than 0 W*/
}
if(n==0)
{
return(1);  /*if number is 0 then Terminate the  condition*/
}
else
{
return(n*fact(n-1));
}
}
```
Output :
Enter Your number to print Factorial 6
Here is the Factorial of given number : 720