C++ Program to find the Factorial of a Number
Program to find the Factorial of a Number
Here we will discuss how to find the factorial of a number entered by the user in C++ programming language.
Factorial of any number is the product of it and all the positive numbers below it for example factorial of 5 is 120
5!=5 x 4 x 3 x 2 x 1
To find the factorial of a number we will use a for loop.
Let’s see how the code works
- User gives an input
- Input is stored in an int type variable say num.
- num is checked for being a negative number if true then input is invalid.
- Otherwise a for loop is started
- The loop starts with i=num
- In every loop cycle i is multiplied by fact and its value is decremented by 1.
- Loop works until i is greater than 0.
- fact is printed as it is the factorial of the given number.
//Factorial of a number
using namespace std;
cout<<"Enter the number: ";
//checking for negative input
cout<<"Invalid input!!\nEnter whole numbers only";
// for positive numbers
cout<<"Factorial of "<<num<<" is "<<fact;
Enter the number: 8
Factorial of 8 is 40320