Open In App

C++ Program to Find Factorial Using Recursion

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The factorial of a number is denoted by “n!” and it is the product of all positive integers less than or equal to n. In this article, we will learn how to find the factorial of a number using recursion in C++.

Example

Input: 5
Output: Factorial of 5 is 120

Factorial Using Recursion in C++

The Factorial of the number is calculated as below:

n! = n × (n−1) × (n−2) × … × 2 × 1

To find factorial using the recursion approach follow the below approach:

  • Define a function to calculate factorial recursively.
  • Create a Base case – if n is 0 or 1, return 1.
  • If n is not 0 or 1, return n multiplied by the factorial of (n-1).

C++ Program to Find Factorial Using Recursion

The below program finds a factorial of a given number using recursion.

C++




// C++ program to find factorial of a number using recursion
#include <iostream>
using namespace std;
  
// Define a function to calculate factorial
// recursively
long long factorial(int n)
{
    // Base case - If n is 0 or 1, return 1
    if (n == 0 || n == 1) {
        return 1;
    }
    // Recursive case - Return n multiplied by
    // factorial of (n-1)
  
    return n * factorial(n - 1);
}
  
int main()
{
    int num = 5;
    // printing the factorial
    cout << "Factorial of " << num << " is "
         << factorial(num) << endl;
  
    return 0;
}


Output

Factorial of 5 is 120

Time Complexity: O(N)
Auxiliary Space: O(N)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads