Factorial program in C++ | Factorial Program Example in C++

Factorial Program in C++: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.

This article guide you for writing a Program in C++ which finds the factorial of given number. Before going to write the C++ program to find the factorial of any number, let’s understand what is Factorial of any number.

Factorial Program in C++: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!. For example:

3! = 3*2*1 = 6
4! = 4*3*2*1 = 24   

Here, 4! is pronounced as “4 factorial”, it is also called “4 bang” or “4 shriek”.

The factorial is normally used in Combinations and Permutations (mathematics).

There are many ways to write the factorial program in C++ language. Let’s see the 2 ways to write the factorial program.

  • Factorial Program using loop
  • Factorial Program using recursion

Armstrong Number program in C++.

Factorial Program using Loop

Let’s see the factorial Program in C++ using loop.

    #include <iostream>  
    using namespace std;  
    int main()  
    {  
       int n,fact=1,number;    
      cout<<"Enter any Number: ";    
     cin>>number;    
      for(n=1;n<=number;n++){    
          fact=fact*n;    
      }    
      cout<<"Factorial of " <<number<<" is: "<<fact<<endl;  
      return 0;  
    }  

Output:

Enter any Number: 4
Factorial of 4 is: 24

Factorial Program using Recursion

Let’s see the factorial program in C++ using recursion.

    #include<iostream>    
    using namespace std;      
    int main()    
    {    
    int factorial(int);    
    int fact,value;    
    cout<<"Enter any number: ";    
    cin>>value;    
    fact=factorial(value);    
    cout<<"Factorial of a number is: "<<fact<<endl;    
    return 0;    
    }    
    int factorial(int n)    
    {    
    if(n<0)    
    return(-1); /*Wrong value*/      
    if(n==0)    
    return(1);  /*Terminating condition*/    
    else    
    {    
    return(n*factorial(n-1));        
    }    
    }  

Output:

Enter any number: 7
Factorial of a number is: 5040
Note: If you interested lo learn C++ through web, You can click here.

Conclusion:

Hi guys, I can hope that you can know that how to write a program in C++ which finds the factorial of given number. If you like this post as well as know something new so share this article in your social media accounts. If you have any doubt related to this post then you ask in comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *