cplusplus

#include <iostream>
using namespace std;

int main() {
    int number, factorial = 1;

    cout << "Enter a positive integer: ";
    cin >> number;

    if (number < 0) {
        cout << "Error! Factorial of a negative number is not defined.";
    } else {
        for (int i = 1; i <= number; ++i) {
            factorial *= i;
        }
        cout << "Factorial of " << number << " = " << factorial;
    }

    return 0;
}

Explanation:

  • #include <iostream>: This line includes the input-output stream header file that allows input and output operations.
  • using namespace std;: This line allows us to use entities like cout and cin without specifying the std namespace.
  • int main() {...}: The program execution starts from here. It's the main function of the program.
  • int number, factorial = 1;: Declares two integer variables number and factorial and initializes factorial to 1.
  • cout << "Enter a positive integer: ";: Prints a message asking the user to enter a positive integer.
  • cin >> number;: Takes user input and stores it in the variable number.
  • if (number < 0) {...}: Checks if the entered number is less than 0.
  • cout << "Error! Factorial of a negative number is not defined.";: If the number is negative, displays an error message since factorial of a negative number is not defined.
  • else {...}: If the number is non-negative, the program enters this block.
  • for (int i = 1; i <= number; ++i) {...}: Starts a for loop initializing i to 1 and iterating until i reaches the value of number.
  • factorial *= i;: Multiplies factorial by i in each iteration.
  • cout << "Factorial of " << number << " = " << factorial;: Prints the factorial value of the entered number.
  • return 0;: Indicates successful termination of the main() function and the program.