Lesson 72 +10 XP

For Loop

For Loop

The for loop puts a counting loop into one tidy line: initialize, test, and update.

The shape

for (init; condition; update) {
  // body
}
  • init runs once, before the loop starts.
  • condition is tested before each trip.
  • If it is true, the body runs.
  • Then update runs, and the condition is tested again.

Counting

for (int i = 0; i < 5; i++) {
  cout << i << endl;
}
  • int i = 0 starts the counter at 0.
  • i < 5 is the stopping condition.
  • i++ adds one after each trip.

This is the classic way to run something exactly five times.

The scoping of i

When the counter is declared in the header, it only exists inside the loop. After the loop ends, i is gone.

for (int i = 0; i < 5; i++) {
  cout << i << endl;
}
// cout << i; // error: i is out of scope here

LearnCpp 8.10 highlights this as a feature: the loop counter stays local. If you need the value later, declare the variable before the loop instead.

TL;DR

  • The header is (init; condition; update).
  • Init runs once, the condition is tested each trip, and update steps between trips.
  • A counter declared in the header is visible only inside the loop.
  • It is the standard type of loop for counting a fixed number of times.