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.

FACTORIAL OF NUMBER IN C++
factorail of number in C++

Algorithm:-

  1. take an input number
  2. Input is stored in an int type variable say num.
  3. Initialize fact =1
  4. num is checked for being a negative number if true then input is invalid.
  5. Otherwise a for loop is started
    1. The loop starts with i=num
    2. In every loop cycle i is multiplied by fact and its value is decremented by 1.
    3. Loop works until i is greater than 0.
  6. fact is printed as it is the factorial of the given 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: 3
Factorial of 3 is 6