Factorial using loops

In this article we will write a C++ that prints the value of the factorial of the number. Write the program using loop and recursion.

First, we will write the program using while loop.

#include<iostream>
using namespace std;
int main(){
	int a=1;
	long f=1;
	cout<<"Enter a positive integer : ";
	cin>>a;
	if(a==0)f=1;
	while(a>0){
		f = f*a;
		a--;
	}
	cout<<"The factorial is "<<f<<endl;
	return 0;
}
output of the above program. It gives the factorial of the number
output of the above program. It gives the factorial of the number

Let us write the program using recursion.

#include<iostream>
using namespace std;
int fact(int n){
	if(n<2){
		return 1;
	}
	else{
		return n*fact(n-1);
	}
}
int main(){
	int f;
	cout<<"Using recursive function"<<endl;
	cout<<"Enter a number : ";
	cin>>f;
	f = fact(f);
	cout<<"The factorial is "<<f;
	return 0;
}
output of the above program. using recursive function
output of the above program. using recursive function

One Reply to “Factorial using loops”

Leave a Reply

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