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:
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
#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:
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
#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: 6
Factorial of a number is: 720