c++ program to find factorial of a number
#include
using namespace std;
int main()
{
unsigned int n;
unsigned long long factorial = 1;
cout << "Enter a positive integer: ";
cin >> n;
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
Explanation
- Here variable factorial is of type
unsigned long long
.
- It is because factorial of a number is always positive, that's why
unsigned
qualifier is added to it.
- Since the factorial a number can be large, it is defined as
long long
.