Cover Image for C++ Program
175 views

C++ Program

The simple C++ program that calculates the factorial of a number entered by the user using a for loop:

C++
#include <iostream>

int main() {
    int num;
    long long factorial = 1;

    std::cout << "Enter a positive integer: ";
    std::cin >> num;

    if (num < 0) {
        std::cout << "Factorial is not defined for negative numbers." << std::endl;
    } else {
        for (int i = 1; i <= num; ++i) {
            factorial *= i;
        }
        std::cout << "Factorial of " << num << " is " << factorial << std::endl;
    }

    return 0;
}

This program does the following:

  1. Includes the <iostream> header for input and output operations.
  2. Defines the main function as the entry point of the program.
  3. Declares an integer variable num to store the user’s input and a long long variable factorial to store the result.
  4. Prompts the user to enter a positive integer.
  5. Reads the user’s input into the num variable using cin.
  6. Checks if the entered number is negative. If it’s negative, it displays a message that factorial is not defined for negative numbers.
  7. If the number is non-negative, it calculates the factorial using a for loop and displays the result.

Compile and run this program, and it will calculate the factorial of the input number.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS