calculate factorial

Here is the code to calculate factorial in C++:

#include <iostream>
using namespace std;

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

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

Explanation:

  1. The code begins with the inclusion of the iostream header file, which allows us to use the input/output stream objects like cin and cout.

  2. The factorial function is defined, which takes an integer n as an argument and returns an integer value. This function calculates the factorial recursively.

  3. Inside the factorial function, there is a base case that checks if n is equal to 0. If it is, the function returns 1, which is the factorial of 0.

  4. If n is not equal to 0, the function recursively calls itself with the argument n - 1 and multiplies the current value of n with the result of the recursive call.

  5. In the main function, an integer variable num is declared to store the user input.

  6. The user is prompted to enter a number using cout and cin is used to take the input and store it in the num variable.

  7. The factorial function is called with the num variable as an argument, and the result is printed using cout. The << operator is used to concatenate the strings and variables together.

  8. Finally, the main function returns 0, indicating successful execution of the program.