Factorial Of Number N
As you may know that the factorial of a positive number is the product of all the integer numbers from 1 up to that particular number say n.
For Example, the factorial of the number 4 can be defined as 4! that is equal to 1*2*3*4 = 24.
Factorial can only be defined for positive integers.
We can only find the factorial of positive numbers, therefore the factorial of a negative number doesn’t exist, and the factorial of 0 is 1.
Example: Factorial of Number 4
The factorial of the positive number 4 is 24 as you can see below.
4! = 1 * 2 * 3 * 4 = 24 Ans.
Factorial of a number n C++ Program
// factorial of a number c++ program
//techindetail.com
#include <iostream>
using namespace std;
int main(){
int n; //to store the user value
//long double bcz the value may be bigger
long double 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 = factorial * i;
}
cout << "Factorial of " << n << " = " << factorial;
}
return 0;
}
Code language: PHP (php)
Output Of Above C++ Program
Enter a positive integer: 4 Factorial of 4 = 24
Enter a positive integer: 5 Factorial of 5 = 120
C++ Program to find the factorial using Recursion
// factorial using recursion
// techindetail.com
#include<iostream>
using namespace std;
int factorial(int n);
int main()
{
int n;
cout << "Enter a Positive Integer: ";
cin >> n;
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
Code language: PHP (php)
Output Of Above C++ Program
Enter an positive integer: 5 Factorial of 5 = 120