Factorial of a number in c plus plus
What is a Factorial?
The factorial of a non-negative integer n
is the product of all positive integers less than or equal to n
.
It is denoted as:
n! = n × (n – 1) × (n – 2) × … × 2 × 1
Examples:
- 0! = 1 (by definition)
- 1! = 1
- 2! = 2 × 1 = 2
- 3! = 3 × 2 × 1 = 6
- 4! = 4 × 3 × 2 × 1 = 24
- 5! = 5 × 4 × 3 × 2 × 1 = 120
using function
#include<iostream>
using namespace std;
int fact(int n)
{
int fact=1;
for(int i=1; i<=n; i++)
{
fact*=i;
}
return fact;
}
int main()
{
cout<<"fact:"<<fact(5)<<endl;
return 0;
}
Iterative Method:
#include<iostream>
using namespace std;
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; ++i)
result *= i;
return result;
}
int main() {
int num;
cout << “Enter a positive integer: “;
cin >> num;
if (num < 0)
cout << "Factorial is not defined for negative numbers." << endl;
else
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}
Recursive Method:
include
using namespace std;
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n – 1);
}
int main() {
int num;
cout << “Enter a positive integer: “;
cin >> num;
if (num < 0)
cout << "Factorial is not defined for negative numbers." << endl;
else
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}
