Introduction to Computer Programming | Source: Comprehensive Guide to For Loops in C++
Difficulty: Beginner | Prerequisites: Variables, data types, basic I/O in C++
Tags: for loop, C++ loop, loop syntax, initialization, condition, update, while loop, iteration, control flow, counting loop, loop variable, increment, decrement
A for loop in C++ bundles three things into one line: where you start, when you stop, and how you step. It is the go-to choice when you know how many times a block of code should run. This section covers the syntax, how for differs from while, the flexibility of the update expression, and a worked factorial example.
For loop
A control structure that repeats a block of code a set number of times. Its header holds the initialisation, the condition, and the update, separated by semicolons.
In simple terms, it is a compact way to say "do this N times" without scattering the counter logic across different lines.
Initialisation (init expression)
The statement that runs once before the loop begins. It usually declares and sets the loop control variable.
Think of it as the starting line of a race: it fires once and never again.
Condition (test expression)
A Boolean expression evaluated before each iteration. If true the body runs; if false the loop ends.
In simple terms, this is the question the loop asks every lap: "Should I keep going?"
Update (increment / step expression)
The expression executed after each iteration. It changes the loop control variable so the loop eventually terminates.
Think of it as the odometer ticking over: it moves the counter closer to the finish.
Loop control variable (counter variable)
The variable that tracks how far the loop has progressed. Declared in the initialisation and modified by the update.
In simple terms, it is the loop's built-in counter.
Iteration
One complete execution of the loop body. A loop that runs 10 times performs 10 iterations.
Infinite loop
A loop whose condition never becomes false, so it runs forever. Usually caused by an update that moves the control variable away from the termination condition.
Off-by-one error (OBOE)
A boundary mistake where the loop runs one time too many or one time too few. Typically caused by confusing < with <= (or vice versa) in the condition.
In simple terms, the loop stops one step early or one step late.
Factorial (n!)
The product of all positive integers from 1 to n. For example, 5! = 1 x 2 x 3 x 4 x 5 = 120.
In simple terms, "multiply every whole number from 1 up to n together."
The for loop packs initialisation, condition, and update into a single header line. The general form:
for (initialisation; condition; update) {
// body
}Execution order on every pass:
Initialisation runs once, before the first iteration.
Condition is checked. If true, the body executes. If false, the loop ends.
After the body completes, the update runs.
Control returns to step 2.
Worked example, printing 0 through 9:
for (int n = 0; n < 10; n++) {
cout << n << endl;
}int n = 0 declares and sets the counter.
n < 10 keeps the loop running while n is below 10.
n++ adds 1 after each iteration.
The body runs 10 times (n = 0, 1, 2, ... , 9).
Both while and for repeat a block, but they organise the loop machinery differently.
While loop separates the three parts across the code:
int n = 0; // initialisation
while (n < 10) { // condition
cout << n << endl;
n++; // update
}Best suited to situations where the number of iterations depends on runtime input or events, and you cannot predict how many passes you need.
For loop keeps everything on one line:
for (int n = 0; n < 10; n++) {
cout << n << endl;
}Preferred when the iteration count is known or calculable before the loop starts.
Aspect | While loop | For loop |
|---|---|---|
Structure | Init outside, condition inside, update inside body | All three in the header |
Typical use | Iteration count unknown or event-driven | Iteration count known or fixed |
Readability | Counter logic spread across lines | Counter logic visible at a glance |
Functionally, any for loop can be rewritten as a while loop and vice versa. The choice is about clarity and convention.
The update expression is not limited to i++. It can perform any arithmetic that moves the control variable.
Decrementing by 1 (counting down):
for (int n = 10; n > 0; n--) {
cout << n << endl;
}Prints 10 down to 1.
Stepping by a larger value (decrement by 5):
for (int i = 100; i >= 5; i -= 5) {
cout << i << endl;
}Counts from 100 down to 5 in steps of 5.
Using a computed step (variables in the update):
// Given x = 2, y = 10
for (int j = x; j <= 4 * x * y; j += y / x) {
// Loop body
}Here y / x evaluates to 5, so j advances by 5 each iteration. The update can be any expression, including multiplication, division, or calls to functions, as long as it eventually makes the condition false.
The factorial of a positive integer n (written n!) is the product of all integers from 1 to n. A for loop handles this neatly because the number of multiplications is known in advance: n - 1.
int n;
cout << "Please enter a positive integer: " << endl;
cin >> n;
int nFactorial = 1;
for (int i = 2; i <= n; i++) {
nFactorial *= i;
}
cout << "Factorial of " << n << " is " << nFactorial << endl;Step-by-step for n = 5:
nFactorial starts at 1.
i = 2: nFactorial = 1 x 2 = 2
i = 3: nFactorial = 2 x 3 = 6
i = 4: nFactorial = 6 x 4 = 24
i = 5: nFactorial = 24 x 5 = 120
Loop ends because i = 6 > 5.
Notice that i starts at 2 (not 1) because multiplying by 1 has no effect. The condition uses <= rather than < to ensure the final multiplication by n is included. Using < here would be an off-by-one error.
Students often think the update runs before the body on the first pass. It does not. The update runs only after each completed iteration; the first pass goes straight from initialisation to condition to body.
Students often assume for and while differ in capability. They do not. Any for loop can be rewritten as a while loop. The difference is readability and convention, not power.
Students sometimes believe the loop variable is available after the loop ends. In standard C++, a variable declared inside the for header (e.g. int i = 0) goes out of scope when the loop finishes. Trying to use it afterwards is a compile error.
Students frequently confuse < and <= in the condition, thinking one extra iteration is harmless. It is not. In a factorial loop, using < instead of <= drops the final multiplication and produces the wrong answer.
Be able to trace through a for loop by hand and state the output. Exam questions routinely give a loop and ask "What does this print?"
Know the execution order: init, condition check, body, update, condition check, body, update, and so on.
Expect a question comparing while and for. The answer centres on structure and readability, not capability.
Off-by-one errors are a favourite exam topic. Be ready to spot whether a condition should use < or <= for a given problem.
The factorial example is a classic exam question. Make sure you can write it from scratch and explain why i starts at 2 and the condition uses <=.
True or false: The update expression in a for loop runs before the first iteration of the body. (False.)
Fill in the blank: A for loop is preferred over a while loop when the number of ______ is known in advance. (iterations)
True or false: for (int i = 0; i < 5; i++) executes the body exactly 5 times. (True.)
Fill in the blank: In the factorial loop for (int i = 2; i <= n; i++), changing <= to < causes a(n) ______ error. (off-by-one)
True or false: A variable declared inside the for header can be used after the loop finishes. (False.)
Q: Write a for loop that prints the even numbers from 2 to 20 inclusive.
A: for (int i = 2; i <= 20; i += 2) { cout << i << endl; }
Q: What is the output of the following code? for (int i = 1; i <= 4; i++) { cout << i * i << " "; }
A: 1 4 9 16
Q: Rewrite this for loop as a while loop: for (int n = 5; n > 0; n--) { cout << n; }
A: int n = 5; while (n > 0) { cout << n; n--; }
Q: Explain why for (int i = 2; i < n; i++) { nFactorial *= i; } gives an incorrect factorial.
A: Using < instead of <= means the loop stops before i reaches n. The final multiplication by n is never performed, so the result is (n-1)! instead of n!.
Q: What value does nFactorial hold after for (int i = 2; i <= 1; i++) { nFactorial *= i; } if nFactorial starts at 1?
A: It stays at 1. The condition i <= 1 is false on the first check (since i starts at 2), so the body never executes. This correctly gives 1! = 1.
For loops connect directly to arrays and vectors: iterating over elements by index is one of the most common uses of a counted loop. Nested for loops appear when you work with two-dimensional arrays or need to compare every pair in a collection. The factorial example reappears in recursion, where the same computation is expressed as a function calling itself rather than as a loop.
for loop C++, C++ loop syntax, initialisation condition update, counting loop, loop control variable, while vs for, loop increment, loop decrement, custom step size, factorial C++, n factorial, iteration, off-by-one error, OBOE, boundary condition, loop counter, control flow, repetition structure, definite loop, count-controlled loop