In this article, you will learn about C++ program to find factorial using recursive function and also without using a recursive function.
We will calculate factorial of a number entered by the user with two different methods.
Let’s see how to calculate factorial of a given number.
Factorial of 5 : 1 * 2 * 3 * 4 * 5 : 120
//C++ program to find factorial
#include <iostream>
using namespace std;
int main()
{
unsigned int num;
unsigned long long fact = 1;
cout << "Enter positive number: ";
cin >> num;
for (int i = 1; i <= num; i++ )
{
fact = fact * i;
}
cout << "Factorial of " << num << ": " << fact << endl;
return 0;
}
Output
Enter positive number: 6 Factorial of 6: 720
//program to calculate factorial using recursion
#include<iostream>
using namespace std;
int fact(int num)
{
if(num <= 1)
return(1);
else
return(num * fact(num-1));
}
int main ()
{
int num;
cout << "Enter a number: ";
cin >> num;
cout << "\nFactorial of " << num << " is " << fact(num) << endl;
return 0;
}
Output
Explanation
In the above program, we have created user-defined function fact
that calculates the factorial of a given number using recursion.