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

    =120

To find the factorial of a number we will use a for loop.

Working

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.
Program to find factorial of a number

C++ Code

//C++ Program
//Factorial of a number
#include<iostream>
using namespace std;
//main program
int main()
{
//initializing variables
int fact=1,num;
cout<<"Enter the number: ";
//user input
cin>>num;
//checking for negative input
if(num<0)
cout<<"Invalid input!!\nEnter whole numbers only";
// for positive numbers
else
{
for(int i=num;i>0;i--)
{
fact*=i;
}
cout<<"Factorial of "<<num<<" is "<<fact;
}
return 0;
}

Output

Enter the number: 8
Factorial of 8 is 40320

Please Login/Signup to comment