Horje
C++ Program to Find Factorial Using Recursion

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)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Find the Mode in a 2D Array in C++? How to Find the Mode in a 2D Array in C++?
How to Take Multiple String Inputs in a Single Line in C++? How to Take Multiple String Inputs in a Single Line in C++?
How to Throw a Custom Exception in C++? How to Throw a Custom Exception in C++?
Search a Multimap in Reverse Order in C++ Search a Multimap in Reverse Order in C++
How to Replace Text in a String Using Regex in C++? How to Replace Text in a String Using Regex in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14