How to find factorial of a number in C++(3 ways)

In this article, we are going to learn about How to find factorial of a number in C++. Before we jump into the code, let us quickly understand What is Factorial of a Number? The Factorial of a given number is the product of a given series of consecutive whole numbers starting with 1 and ending with the given number.

For example, the factorial of n is:
n! = n x (n − 1) x (n − 2) x . . . x 3 x 2 x 1 given by the user

C++ program to find the factorial of a Number


C++ program to find the factorial of a Number.
#include<iostream>
using namespace std;

int Factorial(int n);

int main()
{
	int num;
	long long factorial = 1;
    cout << "Enter a positive number to find Factorial: ";
    cin >> num;
    while (num < 0) 
	{
        cout << "Please Enter a positive number: ";
        cin >> num;
    }
	
	for(int i = 1; i <=num; ++i) 
	{
        factorial *= i;
    }
    cout << "Factorial of " << num << " = " << factorial;
	
	return 0;
}

Output

Enter a positive number to find Factorial: 5
Factorial of 5 = 120

2. C++ program to find the factorial of a Number using Function


#include<iostream>
using namespace std;
int Factorial(int n);

int main()
{
	int num;
	long long factorial = 1;
    cout << "Enter a positive number to find Factorial: ";
    cin >> num;
    while (num < 0) 
	{
        cout << "Please Enter a positive number: ";
        cin >> num;
    }
	
    factorial =Factorial(num); 
     cout<<"\nFactorial of number: "<<num <<" is " <<factorial << endl;
	return 0;
}
int Factorial (int i) 
{
    int result = 1;
    while (i > 0) 
	{
        result = result * i;
        i = i-1;
    }
    return(result);
}

Output

 Enter a positive number to find Factorial: 5

Factorial of number: 5 is 120

3 C++ program to find the factorial of a Number using recursion.


#include<iostream>
using namespace std;

int Factorial(int n);

int main()
{
	int num;
	long long factorial = 1;
    cout << "Enter a positive number to find Factorial: ";
    cin >> num;
    while (num < 0) 
	{
        cout << "Please Enter a positive number: ";
        cin >> num;
    }
	
    factorial =Factorial(num); 
    cout<<"\nFactorial of number: "<<num <<" is " <<factorial << endl;
	return 0;
}
int Factorial(int n)
{
    
    if(n==1)
	{
      return 1;
    }
   else
    {
        return  n=n*Factorial(n-1);
    }
}

Output

 Enter a positive number to find Factorial: 5

Factorial of number: 5 is 120