C++ Program to Find Factorial of a Numbers
In this example, we will learn to Find the Factorial of a number using For Loop and While Loop.
To understand this example, you should have the knowledge of the following C++ programming topics:
Factorial of a Numbers
For any positive number n, it's factorial is given by:
factorial = 1*2*3...*n
Factorial of negative number cannot be found and factorial of 0 is 1.
In this program below, user is asked to enter a positive integer. Then the factorial of that number is computed and displayed in the screen.
Example 1: Program to Find Factorial of a given number using for loop.
// C++ Program to Find the Factorial of a number using For loop.
#include <iostream>
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: 5 Factorial of 5 =120
Working of above Program:
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
.
Example 2: Program to Find Factorial of a given number using while loop
// C++ Program to Find the Factorial of a number using While loop
#include <iostream>
using namespace std;
int main() {
int n, f = 1, i = 1;
cout << "Enter a positive integer: ";
cin >> n;
// Loop to calculate the factorial of a number
while (i <= n) {
f=f*i;
++i;
}
cout << "Factorial of " << n << " = " << f;
return 0;
}
Output
Enter a positive integer: 5 Factorial of 5 =120
Here variable f is of type int
.
It is because factorial of a number is always positive, that's why unsigned
qualifier is added to it.
Working of above Program:
- First the computer reads the number to find the factorial of the number from the user.
- Then using while loop the value of ‘i’ is multiplied with the value of ‘f’.
- The loop continues till the value of ‘i’ is less than or equal to ‘n’. Finally the factorial value of the given number is printed.
Next Example
We hope that this Example helped you develop better understanding of the concept of "Find Factorial" in C++.
Keep Learning : )
In the next Example, we will learn about C++ Program to Generate Multiplication Table
.