Factorial Program In C++ - C++ Programming Tutorial
C++ Course / C++ Programs / Factorial Program In C++

Factorial Program In C++

BLUF: Mastering Factorial Program In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Factorial Program In C++

C++ is renowned for its efficiency. Learn how Factorial Program In C++ enables low-level control and high-performance computing in the tutorial below.

The Factorial Program in C++ calculates the factorial of a given number, which is the multiplication of all positive integers in descending order. The factorial of a number 'n' is represented as 'n!'. For instance:

Example

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

6! = 6*5*4*3*2*1 = 720

Here, the expression 4! is spoken as "4 factorial", it is alternatively referred to as "4 bang" or "4 shriek".

Factorials are typically utilized in the fields of Combinations and Permutations within the realm of mathematics.

Two methods to implement the factorial program in C++ are as follows:

  • Generating the factorial using a loop
  • Calculating the factorial using recursion
  • Factorial Program using Loop

Let's explore the factorial Program in C++ utilizing a loop.

Example

Example

#include <iostream>

using namespace std;

int main()

{

   int i,fact=1,number;  

  cout<<"Enter any Number: ";  

 cin>>number;  

  for(i=1;i<=number;i++){  

      fact=fact*i;  

  }  

  cout<<"Factorial of " <<number<<" is: "<<fact<<endl;

  return 0;

}

Output:

Output

Enter any Number: 5  

 Factorial of 5 is: 120

Factorial Program using Recursion

Let's explore the factorial function implemented in C++ using recursion.

Example

Example

#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:

Output

Enter any number: 6   

Factorial of a number is: 720

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience