C++ Online Compiler
Example: Factorial without Recursion using For Loop in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Factorial without Recursion using For Loop #include <iostream> int main() { int number; long long factorial = 1; // Use long long for larger factorials // Step 1: Prompt user for input std::cout << "Enter a non-negative integer: "; std::cin >> number; // Step 2: Handle special cases for 0 and negative numbers if (number < 0) { std::cout << "Factorial is not defined for negative numbers." << std::endl; } else if (number == 0) { factorial = 1; // Factorial of 0 is 1 std::cout << "The factorial of " << number << " is: " << factorial << std::endl; } else { // Step 3: Calculate factorial using a for loop for (int i = 1; i <= number; ++i) { factorial *= i; // Multiply factorial by current number } // Step 4: Display the result std::cout << "The factorial of " << number << " is: " << factorial << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS