FACTORIAL IN C++

Factorial in C++

#include <iostream>
using namespace std;

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

int main() {
    int number;
    cout << "Enter a positive integer: ";
    cin >> number;
    cout << "Factorial of " << number << " = " << factorial(number);
    return 0;
}
  1. Include Libraries:
  2. Include the iostream library for input/output operations.

  3. Namespace:

  4. Use the "std" namespace for standard C++ library objects.

  5. Factorial Function:

  6. Define a recursive function to calculate the factorial of a number.
  7. If the input is 0 or 1, return 1.
  8. Otherwise, calculate the factorial using recursion.

  9. Main Function:

  10. Declare a variable "number" to store the input.
  11. Prompt the user to enter a positive integer.
  12. Read the input and store it in the "number" variable.
  13. Calculate the factorial using the "factorial" function and display the result.

  14. Return Statement:

  15. Return 0 to indicate successful execution of the program.