🔢 Factorial of a Number Using Loop in C++
A factorial is a mathematical operation that multiplies a number by every positive number below it. In C++, calculating a factorial using a loop is one of the simplest and most common programming exercises for beginners.
📘 What Is a Factorial?
The factorial of a non-negative integer n
, written as n!
, is defined as:
n! = n × (n - 1) × (n - 2) × ... × 1 Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
Factorials are used in mathematics, especially in permutations, combinations, and other algorithmic problems.
📄 C++ Code to Find Factorial Using Loop
#include <iostream>
using namespace std;
int main() {
int number;
unsigned long long factorial = 1;
// Input from user
cout << "Enter a positive integer: ";
cin >> number;
// Error check
if (number < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
for (int i = 1; i <= number; ++i) {
factorial *= i;
}
// Output result
cout << "Factorial of " << number << " = " << factorial << endl;
}
return 0;
}
✅ Sample Output
Enter a positive integer: 6 Factorial of 6 = 720
🧠 Explanation
- Step 1: Take input from the user.
- Step 2: Check if the number is negative (factorials aren't defined for negatives).
- Step 3: Use a
for
loop to multiply the number down to 1. - Step 4: Display the result.
📘 Definition: Factorial Using Loop
Calculating a factorial using a loop in C++ is a method where a repeated multiplication is performed using a for
or while
loop.
It avoids recursion and is generally easier to implement and understand for beginner-level programmers.
This technique is especially useful for iterative computations and number-based logic tasks.
🎯 Final Thoughts
The factorial loop program is not only a classic beginner example but also a practical one used in real-world algorithms. By learning how to compute factorials using loops, programmers strengthen their foundation in iteration, logic, and algorithm design.
Post a Comment