Finding factorial using recursion is not any rocket science, Here I am going to explain both methods. But let’s have a look at what factorial and recursion is.

*Factorial*:

*Factorial*

factorial of number is defined as,

Product of number and all the integers below it

Factorial is an important concept and widely used in competitive programming. Let’s take an example of Factorial.

** Calculate Factorial of number 5**! : =

*5 * 4 * 3 * 2 * 1 = 120.*** Calculate Factorial of number 8! : = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5760**.

*Formula of Factorial of Number n! = n * (n-1) * (n-2) * (n-3) * ……. * 1;*

** Note: Factorial of 0 is 1** remember this, It is the key point of creating program of factorial using recursion.

** Historical Point 1: The notation n! was introduced by the French mathematician Christian Kramp in 180**8.

*Advantage Of Factorial *

*Advantage Of Factorial*

- Factorial is extensively used in Number Theory
- It is also used in Probability

*Recursion:*

*Recursion:*

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function.

*Prerequisite:*

*Prerequisite:*

** You must have knowledge of User Defined Function, Recursion for understanding factorial using recursion**.

*Program of Factorial Using For Loop*:

*Program of Factorial Using For Loop*

As we learn above the formula of calculating the factorial, and using this we can create simple algorithm.

```
int fact(int n)
{
int f = 1;
for(int i = n;i>=1;i--)
{
f = f * i;
}
return f;
}
```

This is the simple function for creating factorial, Below is the complete program with the Input and Output

*Program*

*Program*

```
#include <bits/stdc++.h>
using namespace std;
int fact(int n)
{
int f = 1;
for(int i = n;i>=1;i--)
{
f = f * i;
}
return f;
}
int main ()
{
int n;
cout<<"Enter Number\n";
cin>>n;
cout<<"Factorial is "<<fact(n);
return 0;
}
```

*Input:*

Enter Number 5

*Output:*

```
Factorial is120
```

## Program Of Factorial Using Recursion:

Note one point that the factorial of any number is equal to number * factorial of (number – 1). Example:* factorial of 5 is 5 * 4!.*

This is the main principle behind this, but recursion also need base condition to return on first call.

```
int fact(int n)
{
if(n==0 || n==1)
return 1;
return n*fact(n-1);
}
```

** if(n == 0) or if( n==1) we simply return 1 and this is the base condition**. if n is greater than 1 we again call function for n-1.

Complete program of factorial using recursion is given below

### Program

```
#include <bits/stdc++.h>
using namespace std;
int fact(int n)
{
if(n==0 || n==1)
return 1;
return n*fact(n-1);
}
int main ()
{
int n;
cout<<"Enter Number\n";
cin>>n;
cout<<"Factorial is "<<fact(n);
return 0;
}
```

*Input:*

Enter Number: 5

*Output:*

Factorial is 120: