C++ Program to Calculate the Factorial of a Number Using Recursion

11/05/2024 0 By indiafreenotes

Calculating the factorial of a number using recursion in C++ is a common example used to demonstrate the concept of recursion in programming. The factorial of a non-negative integer 𝑛n is denoted by 𝑛!n!, which is the product of all positive integers less than or equal to 𝑛n. The recursive relationship can be defined as:

n! = n × (n−1)!

with the base case being: 0!=10!=1

Here’s a simple C++ program that calculates the factorial of a number using this recursive approach:

#include <iostream>

// Function to calculate factorial recursively

long long factorial(int n) {

    if (n == 0)  // Base case: factorial of 0 is 1

        return 1;

    else

        return n * factorial(n – 1);  // Recursive case

}

int main() {

    int number;

    std::cout << “Enter a positive integer: “;

    std::cin >> number;

    // Check for negative numbers

    if (number < 0) {

        std::cout << “Factorial of a negative number doesn’t exist.” << std::endl;

    } else {

        long long fact = factorial(number);

        std::cout << “Factorial of ” << number << ” is ” << fact << std::endl;

    }

    return 0;

}

Key Points of the Program

  • Function Definition:

The factorial function takes an integer n and returns its factorial. It returns a long long to handle larger results since factorial values grow extremely fast.

  • Recursion:

The function calls itself with n – 1 until it reaches the base case where n equals 0. At that point, it returns 1.

  • Input Handling:

The main function prompts the user to enter a positive integer, reads this input, and then checks if the input is negative. Factorials of negative numbers are not defined, so it provides an appropriate message in that case.

  • Output:

If the input is non-negative, the program calculates the factorial using the recursive function and displays the result.

  • Efficiency and Limitations:

Although recursion is a straightforward way to calculate factorial, it may not be the most efficient method for very large numbers due to potential stack overflow issues with deep recursion. For extremely large numbers, iterative solutions or using languages/libraries that support big integers and tail recursion optimizations might be more suitable.