Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n.
For example: The factorial of 7 is 5040.
7! = 7 * 6 * 5 * 4 * 3 * 2 *1 7! = 5040
Let us see the code to calculate the factorial of a number using recursion.
Example
#include <iostream>
using namespace std;
int fact(int n) {
if ((n==0)||(n==1))
return 1;
else
return n*fact(n-1);
}
int main() {
cout<<"Factorial of 5 is "<<fact(5)<<endl;
cout<<"Factorial of 3 is "<<fact(3)<<endl;
cout<<"Factorial of 7 is "<<fact(7)<<endl;
return 0;
}Output
Factorial of 5 is 120 Factorial of 3 is 6 Factorial of 7 is 5040
In the above program, the function fact() is a recursive function. The main() function calls fact() using the number whose factorial is required. This is demonstrated by the following code snippet.
cout<<"Factorial of 5 is "<<fact(5)<<endl; cout<<"Factorial of 3 is "<<fact(3)<<endl; cout<<"Factorial of 7 is "<<fact(7)<<endl;
If the number is 0 or 1, then fact() returns 1. If the number is any other, then fact() recursively calls itself with the value n-1. Along with calling itself recursively, fact() multiplies n with the recursive call fact(n-1). This yields.
n*(n-1)*(n-2)....3*2*1 or the factorial of n
This is demonstrated using the following code snippet.
int fact(int n) {
if ((n==0)||(n==1))
return 1;
else
return n*fact(n-1);
}