Classic for Loop
With a while loop, the setup is scattered:
int i = 1;while (i <= 10) { std::cout << i << " "; i++;}The initialization (i = 1) is on one line, the stopping condition (i <= 10) is on another, and the step that moves you closer to stopping (i++) is inside the loop body.
This pattern, consisting of three parts, comes up so often that C++ gives it its own shorthand, called the for loop. It groups all three parts together in one place so the code feels compact and easier to grasp.
The three-part structure
Here’s a for loop that prints the squares of the first ten positive integers.
The parentheses hold three parts, separated by semicolons:
- Initialization:
int i = 1;runs once, before the loop starts. - Condition:
i <= 10is evaluated before every iteration. As long as it’strue, the loop keeps going. - Increment:
i++runs at the end of every iteration, after the loop’s body executes.
A loop that counts down
There’s nothing forcing you to count up by one. Here’s a countdown timer, ticking from 5 down to 1:
seconds is decremented after each iteration, and the stopping condition is now seconds > 0.
Skipping values
While a plain increment or decrement is the most common use, the third part can be any expression that changes the loop variable. Here’s one that moves two steps forward instead of one:
In fact, all three parts are independent expressions.
What you can leave out
The three parts of a for loop are optional. The semicolons still have to be there, but any (or all) of the parts between them can be empty:
int i = 0;for (; i < 10; i++) { // "i" is already declared above, so no init needed here}Leaving out the initialization like this is rare in practice, but you’ll see this when reading other people’s code. At the other extreme, omitting all three parts gives you for (;;), which loops forever, exactly like while (true).
A quick word on scope
The variable you declare in the initialization part, like i in the example below, only exists for as long as the loop runs, and disappears once the loop ends:
for (int i = 0; i < 5; i++) { // i is usable here}// i is gone by this point, trying to use it here is a compile errorThis is deliberate. So, if you need a counter for one loop and want to reuse the name i for a different loop later, you can declare it again without a problem.
Checkpoint
You want a loop that prints every number from 100 down to 0, in steps of 10. Which for loop header does this correctly?
A loop needs to run exactly 50 times, starting its counter i at 0 and incrementing by 1 after each iteration. What does the stopping condition need to be?