Write a C++ program to Calculate Factorial of a Number Using Recursion

In C++, a recursive function is one that calls itself within its own definition.

This can be useful for solving problems that can be broken down into smaller, similar problems.

One such problem is calculating the factorial of a number.

The factorial of a number is the product of all positive integers up to that number.

For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1, or 120. We can use recursion to calculate the factorial of a number as follows:

#include <iostream>

int factorial(int n) {
    if (n == 0) {
        return 1;
    } else {
        return n * factorial(n-1);
    }
}

int main() {
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;
    std::cout << "Factorial of " << num << " is " << factorial(num) << std::endl;
    return 0;
}

In the factorial() function, we check if the input n is 0. If it is, we return 1, since the factorial of 0 is 1. If n is not 0, we return n multiplied by the factorial of n-1. This recursion continues until we reach the base case of n=0.

In the main() function, we prompt the user to enter a number and store it in the variable num. We then call the factorial() function with num as the argument, and output the result.

This program uses a simple recursive function to calculate the factorial of a number in C++. With recursion, we can solve many problems that are difficult or impossible to solve using other methods.