Calculate the Factorial of a Number Using a Loop in C++
The factorial of a number $N$ (denoted as $N!$) is the product of all positive integers less than or equal to $N$. For example: $5! = 5 \times 4 \times 3 \times 2 \times 1 = 120$.
Iterative Logic
The For Loop
A for loop is used to repeat the multiplication process exactly $N$ times, starting from 1 up to the input number.
Accumulator Variable
We initialize a factorial variable to 1. During each iteration, we update it using the *= operator.
Key Concepts Learned:
- Loop Iteration: Using
forloops for mathematical series. - Compound Assignment: Using
*=to multiply and assign values efficiently. - Algorithm Design: Converting a mathematical formula ($N!$) into executable code.
Course:
Control Flow & Logic
Step-by-Step Objective
- Prompt the user to enter a positive integer $N$.
- Initialize an
intvariable namedfactorialto 1. - Use a
forloop starting fromi = 1up toN. - Multiply the
factorialvariable byiin each step. - Display the final result to the console.
C++ Solution
factorial_loop.cpp
Iterative Logic
#include <iostream>
using namespace std;
int main() {
int N;
long long factorial = 1; // Use long long for larger results
cout << "Enter a positive integer: ";
cin >> N;
// Use a for loop to calculate the factorial
for (int i = 1; i <= N; ++i) {
factorial *= i; // multiply result by current index
}
cout << "The factorial of " << N << " is: " << factorial << endl;
return 0;
}
Console Output:
Enter a positive integer: 5
The factorial of 5 is: 120
Flow Control & Loops