This C++ program is an example to find the factorial using recursion.
The factorial of a number is defined as the product of all integers from 1 to that number. We cant able to find factorial for negative numbers and for zero is one. An exclamation mark indicates the factorial of a number '!'. For example, 5! = 1*2 *3*4*5 = 120.
n! = 1 * 2 * 3 * 4 *……..* n.
Recursion is the process in which a function will call itself continuously until some conditions are met. To prevent infinite recursion, the if...else statement (or similar approach) can be used
To know more about recursion in C++ please visit our tutorial on recursion.
For finding the factorial, we ask the user to enter a positive integer and read the number to the variable. Define a recursive function factorial ( ) to find the factorial of the number. Pass the entered number to the factorial function.
int factorial(int n)
In this function, the number n is multiplied by the factorial of ( n – 1 ). For this, the number (n – 1) is passed again to the factorial () function, until the value reaches 1. Finally, print the result as factorial.
Step 1: Call the header file iostream
.
Step 2: Use the namespace std.
Step 3: Define a function factorial ( );
n * factorial ( n – 1) until n > 1;
return the value
else return 1;
Step 4: Open the integer type main function; int main().
Step 5: Declare integer variables; n;
Step 6: Print a message to enter a positive integer not greater than 12.
Step 7: Read the value into the variable n;
Step 8: Call the function factorial(n);
Step 9: Exit;
#include<iostream>
using namespace std;
int factorial(int n);
int main() {
int n;
cout << "Enter a positive integer less than 12: ";
cin >> n;
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
int factorial(int n) {
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
Enter a positive integer less than 12: 6 Factorial of 6 = 720