In this post, we will learn how to find the factorial of a number using C++ Programming language. But before that, let’s learn about factorials.
The factorial of a number is the product of all integers from 1 to that number. For example, the factorial of 5 is 5! = 5 x 4 x 3 x 2 x 1 = 120.
We will calculate the factorial of a number entered by the user using the following approaches:
- Using For Loop
- Using While Loop
So, without further ado, let’s begin this tutorial.
C++ Program to Find Factorial of a Number
// C++ Program to Find Factorial of a Number #include <iostream> using namespace std; int main(){ int num, fact = 1; // Asking for input cout << "Enter a number to find the factorial: "; cin >> num; // Finding factorial of a number for (int i = 1; i <= num; i++){ fact = fact * i; } // Displaying output cout << "Factorial of " << num << " is: " << fact << endl; return 0; }
Output
Enter a number to find the factorial: 4
Factorial of 4 is: 24
How Does This Program Work?
int num, fact = 1;
In this program, we have declared two integer data type variables named num and fact. The fact variable has assigned a value of 1.
// Asking for input cout << "Enter a number to find the factorial: "; cin >> num;
The user is asked to enter a number. The entered value gets stored in the num named variable.
// Finding factorial of a number for (int i = 1; i <= num; i++){ fact = fact * i; }
We use a for loop to calculate the factorial of the entered number. Suppose the user enters a number such that num = 4.
Now, to find the factorial of 4!, we perform:
- 1st For Loop Iteration: for (int i = 1; i <= 4; i++)
- fact = fact * i = 1 * 1 = 1.
- 2nd For Loop Iteration: for (int i = 2; i <= 4; i++)
- fact = fact * i = 1 * 2 = 2.
- 3rd For Loop Iteration: for (int i = 3; i <= 4; i++)
- fact = fact * i = 2 * 3 = 6.
- 4th For Loop Iteration: for (int i = 4; i <= 4; i++)
- fact = fact * i = 4 * 6 = 24.
5th For Loop Iteration: for (int i = 5; i <= 4; i++), here the condition is False, so the loop terminates and we get fact = 24.
// Displaying output cout << "Factorial of " << num << " is: " << fact << endl;
The factorial of the entered number is displayed on the screen using the cout statement.
C++ Program to Find Factorial of a Number Using While Loop
// C++ Program to Find Factorial of a Number Using While Loop #include <iostream> using namespace std; int main(){ int num, i = 1, fact = 1; // Asking for input cout << "Enter a number: "; cin >> num; // Calculating factorial using while loop while (i <= num){ fact = fact * i; i++; } // Displaying output cout << "The factorial of " << num << " is: " << fact << endl; return 0; }
Output
Enter a number: 6
The factorial of 6 is: 720
Conclusion
I hope after going through this post, you understand how to find the factorial of a number using C++ Programming language.
If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to assist you.
Also Read: