C++ For Loop
A for loop repeats a block of C++ code while a condition remains true. It is most useful when you know, or can calculate, how many times the loop should run.
A for loop keeps the loop counter setup, test, and update in one line. This makes counting loops compact and easy to read.
Basic Syntax
A for loop has three parts inside the parentheses: an initializer, a condition, and an update. The initializer usually creates and sets a counter variable. The condition is checked before each repetition. The update runs after each repetition of the loop body.
The loop body runs only while the condition is true. When the condition becomes false, the loop stops and the program continues after the closing brace.
Counting With a For Loop
This example prints the numbers from 1 through 5. The variable i is the loop counter.
#include <iostream>
int main(void) {
for (int i = 1; i <= 5; i++) {
std::cout << i << std::endl;
}
return 0;
}
Output:
1
2
3
4
5
The loop starts by setting i to 1. Before each run, C++ checks i <= 5. After the body runs, i++ increases i by one. When i becomes 6, the condition is false and the loop ends.
How the Parts Run
- The initializer runs once before the loop starts.
- The condition is checked.
- If the condition is true, the loop body runs.
- The update runs after the body.
- C++ checks the condition again.
This order is important. The update does not happen before the first run of the loop body. It happens after each completed repetition.
Using a For Loop With Repeated Work
A for loop is often used to repeat the same calculation for a sequence of values. This program adds several prices to a running total.
#include <iostream>
int main(void) {
int total = 0;
for (int price = 10; price <= 30; price += 10) {
total += price;
std::cout << "Added " << price << ", total is " << total << std::endl;
}
return 0;
}
Output:
Added 10, total is 10
Added 20, total is 30
Added 30, total is 60
Here, price += 10 adds 10 to price after each repetition. The loop runs for 10, 20, and 30, then stops when price becomes 40.
Common Mistakes
- Using the wrong comparison, such as
i < 5when you need to include5. - Forgetting the update expression, which can create an infinite loop.
- Changing the counter inside the loop body in a way that makes the loop harder to understand.
- Putting a semicolon immediately after the loop header, such as
for (int i = 0; i < 3; i++);.
When To Use For
Use a for loop when the repetition follows a clear count or step. Use a while loop when the stopping point depends more on a changing condition than on a simple counter.
Takeaway: a for loop is a compact way to initialize a counter, test a condition, update the counter, and repeat a block of code.
