C++ for Beginners: C++ program to Calculate Factorial of a Number Using Recursion

Hits: 9

(C++ programming Example for Beginners)

C++ program to Calculate Factorial of a Number Using Recursion

Example to find factorial of a non-negative integer (entered by the user) using recursion.


This program takes a positive integer from user and calculates the factorial of that number. Suppose, user enters 6 then,

Factorial will be equal to 1*2*3*4*5*6 = 720

You’ll learn to find the factorial of a number using a recursive function in this example.

Example: Calculate Factorial Using Recursion


#include<iostream>
using namespace std;

int factorial(int n);

int main(){
    int n;

    cout << "Enter a positive integer: ";
    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;
}

Output

Enter an positive integer: 6
Factorial of 6 = 720

In the above program, suppose the user inputs a number 6. The number is passed to the factorial() function.

In this function, 6 is multiplied to the factorial of (6 – 1 = 5). For this, the number 5 is passed again to the factorial() function.

Likewise in the next iteration, 5 is multiplied to the factorial of (5 – 1 = 4). And, 4 is passed to the factorial() function.

This continues until the value reaches 1 and the function returns 1.

Now, each function returns the value back to compute 1 * 2 * 3 * 4 * 5 * 6 = 720, which is returned to the main() function.

 

C++ for Beginners: C++ program to Calculate Factorial of a Number Using Recursion

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.