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
- Simple MENU Program in C++
- C and C++ Print ASCII Values of single or all characters
- C Program to find max of three numbers
- Hello world Program in C++
- How to get user input in C++(5 ways)
- Convert String to Hex in C++ using std::hex
- C++ Program to Add Two Numbers
- C++ add two numbers by value or by reference
- C++ program to add two numbers using class
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