*590*

Table of Contents

In this article, you’ll learn about how to make C++ Program to Find Factorial.

### What is the factorial of a number?

Factorial of a non-negative integer is the multiplication of all positive integers smaller than or equal to n, i.e. factorial of 5 is 5*4*3*2*1 which is 120.

The factorial of a negative number doesn’t exist. And the factorial of **0** is **1**.

## Program to find the factorial of a given number using for loop

```
#include <iostream>
using namespace std;
int main() {
int n;
long factorial = 1.0;
cout << "Enter a positive integer: ";
cin >> n;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i) {
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
}
return 0;
}
```

## Output

Enter a positive integer: 4 Factorial of 4 = 24

In the above program, we take a positive integer from the user and compute the factorial using `for`

loop. We print an error message if the user enters a negative number.

## Program to find the factorial of a given number using recursion

```
#include <iostream>
using namespace std;
int fact(int n){
if(n>0)
{
return n*fact(n-1);
}
else
return 1;
}
int main() {
int num;
cin>>"Enter an integer to compute the factorial "
cout<<fact(num);
return 0;
}
```

A factorial is represented by a number and a ” ! ” mark at the end. It is widely used in permutations and combinations to calculate the total possible outcomes. A French mathematician Christian Kramp firstly used the exclamation.