Factorial function c++: In the previous article, we have discussed C++ Program to Generate Random Numbers. In this article, we will see C++ program to Find Factorial of a Number Using Recursion.
C++ program to Find Factorial of a Number Using Recursion
- Write a C++ program to find factorial of a number using recursion.
- Recursive algorithm to calculate factorial of a number.
In this C++ program, we will find factorial of a number using recursion.
The factorial of a integer N, denoted by N! is the product of all positive integers less than or equal to n.
N! = 1 x 2 x 3 x 4….x (N-2) x (N-1) x N
For Example :
6! = 6 * 5 * 4 * 3 * 2 * 1 = 720. 0! = 1 1! = 1
NOTE : Factorial does not exist for negative numbers and factorial of 0 is 1.
The expression to calculate factorial obeys recursive sub-structure property, hence we can use use recursion to calculate factorial.
Let factorial(N) is a function to calculate the value of N!. To find factorial(N) we can first calculate factorial(N-1) then multiply it with N.
N! = 1 x 2 x 3 x 4....x (N-2) x (N-1) x N N! = (N-1)! x N factorial(N) = factorial(N-1) x N
Function factorial(N) reduces the problem of finding N! into sub-problem of finding (N-1)! first and then multiplying it with N to get N!. It keeps on reducing the domain of the problem until N becomes zero.
C++ program to Calculate Factorial of a Number Using Recursion
// C++ program to Calculate Factorial of a Number // Using Recursion #include <iostream> using namespace std; int getFactorial(int N); int main(){ int N; cout << "Enter a Number\n"; cin >> N; cout << "Factorial of " << N << " = " << getFactorial(N); return 0; } // Recursive function to find factorial of a number int getFactorial(int N){ // Recursion Termination condition if(N <= 1){ return 1; } return N * getFactorial(N - 1); }
Output
Enter a Number 5 Factorial of 5 = 120
In above program, we are using a recursive function getFactorial(N) to calculate the factorial of N. If N <= 1, then getFactorial function returns 1, (this is the recursion termination condition) otherwise, it recursively calls itself to calculate factorial of N-1 and multiply it with N to get N!.
Inside main function, we first take a number as input from user using cin ans store it in a variable N. Then we call getFactorial function by passing N as parameter to calculate N!. Above c++ program cannot be used to calculate factorial of large numbers because factorial of such numbers exceeds the range of int data type.
Learn and explore basic C++ Practice Programs that help to enhance your skills & knowledge of the programming language. Get to know how to write simple and clear code on this page.