Calculate Factorial of a Number Using Recursion in C++



In this article, we'll show you how to write a C++ program to calculate the factorial of a number using recursion . The factorial of a number is the result of multiplying all the positive numbers from 1 to that number. It is written as n! and is commonly used in mathematics and programming.

Let's understand this with a few examples:

//Example 1
Input:
5
The factorial of 5 is: 5 * 4 * 3 * 2 * 1 = 120
Output:
120

//Example 2
Input:
6
The factorial of 6 is: 6 * 5 * 4 * 3 * 2 * 1 = 720
Output:
720

Using Recursion To Calculate Factorial

To calculate the factorial of a number, we multiply all the numbers from 1 up to that number. We use recursion, which means the function calls itself with smaller numbers each time until it reaches a base case, where it stops.

Below are the steps we took:

  • First, we create a function called factorial() that takes an integer n as input.
  • Then, we check if the number n is 0. If it is, we return 1. This is the base case where recursion stops.
  • Next, if n is not 0, we return n multiplied by the factorial of n - 1. This step keeps breaking the problem into smaller parts.
  • Finally, the function continues to call itself until the base case is reached, and the results are multiplied one by one as it returns.

C++ Program to Calculate Factorial Using Recursion

Here's the complete C++ program where we implement the approach mentioned above:

#include <iostream>
using namespace std;

int factorial(int n) {
    if (n == 0)  // Base case: when n is 0, return 1
        return 1;
    return n * factorial(n - 1);  // multiply n by the result of factorial(n - 1)
}

int main() {
    int n = 5;
    cout << "Factorial of " << n << " using recursion is: " << factorial(n) << endl;
    return 0;
}

Once you run the above program, you will get the following output, which shows the factorial of 5 calculated using recursion.

Factorial of 5 using recursion is: 120

Time Complexity: O(n) because the function calls itself n times.

Space Complexity: O(n) due to the recursive call stack, which grows to a depth of n.

Updated on: 2025-05-09T15:49:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements