Calculate Factorial of a Number Using Recursion with C++

04-11-17 Course- CPP

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

Instead of using loops to calculate factorial, this program uses recursive function to calculate the factorial of a number.

 

Source Code to Calculate Factorial Using Recursion


/* Source code to find factorial of a number. */

#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);
}

Output


Enter an positive integer: 6
Factorial of 6 = 720