In this post, you will learn how to Find Factorial of a Number Using Recursion in C++ programming language.
This lesson will teach you how to Find Factorial of a Number Using Recursion, with a recursion statement, mathematical operations and decision making statement using the C++ Language. Let’s look at the below source code.
How to Find Factorial of a Number Using Recursion?
RUN CODE SNIPPETSource Code
#include<iostream> using namespace std; int factorial(int n) { if(n > 1) return n * factorial(n - 1); else return 1; } int main() { int n; cin >> n; cout << "Enter a positive integer: "<<n<<endl; cout << "\nFactorial of the number " << n << " is: " << factorial(n); return 0; }
Input
6
Output
Enter a positive integer: 3 Factorial of the number 3 is: 6
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function.
- When function is called within the same function, it is known as recursion. In this program we find out the sum of the first n numbers, using recursion.
- In this code we have two sections, in the first one we declare the function
int factorial(int n)
to initiate the recursive function, where we declare the variable n as an integer. - Using the decision making statements assign the condition to verify if the value of n is greater than 1. If the condition is satisfied then the
return n * factorial(n - 1)
is executed. If not the execution moves to the else statement which returns the value 1. - Here the value of factorial holds the number for which we have to find the factorial. The execution starts by default with 1 (n). The value is verified with the if condition, when the condition is true the value is used in the mathematical function
return n * factorial(n - 1)
or else it returns the value 1. - The function is repeated with the recursion function till the condition is not true.
- The function then moves to the output section of the code, where we use output statements to display the answer stored in
factorial(n).
Note: The ‘ << endl ‘ in the code is used to end the current line and move to the next line and ‘\n’ is also a new line function, to understand how both the functions work exclude it from the code, move it around and work with it.