CPP Tutorial

CPP examples programs

CPP program to print factorial of a number

The below program prints factorial of a number using a loop and using recursion. The CPP cout object is used to output the result on the screen. The factorial of a number can be calculated for positive integers only and is represented by n!.

n! = n*(n-1)*(n-2)*……*1

0! = 1

Code: Using Loop

#include <iostream.h>
using namespace std;
 
int main()  
{  
int num,i;
int f = 1;    
 
cout << "Enter a number:";    
cin >> num;  
 
for (i=num; i>1; i--)   
f = f * i;  
 
cout << num << "!" << "=" << f;  
return 0;
}

Output

Enter a number:10                   
10!=3628800

Code: Using Recursion

#include <iostream.h>
using namespace std;
 
int main()  
{  
int x;
cout << "Enter a Number: ";
cin >> x;
int factorial(int);  
int fact=factorial(x);  
cout<<"Factorial of " << x << " is: "<<fact<<endl;  
return 0;  
}  
 
int factorial(int n)  
{  
if(n<0)  
return(-1);   
if(n==0)  
return(1);  
else  
{  
return(n*factorial(n-1)); 	 
}  
}

Output

Enter a Number: 10            
Factorial of 10 is: 3628800