In this tutorial you will learn about the C++ program to Calculate Factorial of a Number Using Recursion and its application with practical example.
C++ program to Calculate Factorial of a Number Using Recursion
In this tutorial, we will learn to create a C++ program that will Calculate Factorial of a Number Using Recursion using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- Conditional Statements in C++ programming.
- Arithmetic operations in C++ Programming.
What is factorial?
The factorial means the product of the input number and its below integer value up to 1.
1 2 3 4 5 |
For example:- Factorial of 5 means Factorial = 5 * 4 * 3 * 2 * 1 Hence, the factorial will be 120. |
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the required variables for the program. 2. Sending message to enter a number for finding the factorial of the number. 3. Taking the input number from the user for factorial. 4. Calculating Factorial of a Number Using Recursion of that number. 5. Printing the result numbers. 6. End Program. |
Program to Calculate Factorial Using Recursion
Today, we will create a C++ program that will take the input number from the user and then will find the factorial for the input integer value using a recursion program.
Program Code:–
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include<iostream> using namespace std; //user-defined function for factorial int factorial(int no); int main() { //declaring the variable for the program. int no; //no = it will hold the integer value number from the user for finding factorial . //Taking the input number from the user. cout << "Enter a positive integer: "; cin >> no; //printing the output for the program. cout << "Factorial of " << no << " = " << factorial(no); return 0; } int factorial(int no) { if(no > 1) return no * factorial(no - 1); else return 1; } |
Output:-
In the above program, we have first initialized the required variable.
- no = it will hold the integer value.
Program Logic Code to print.