C++ ยท Chapter 18 of 49

C++ For Loop

The classic `for` loop packs initialisation, condition, and increment into one line: `for (init; condition; increment)`. This makes it ideal when you know how many times to repeat something.

C++11 introduced the range-based for loop, `for (auto x : container)`, which iterates over every element of an array, vector, or string without manual indexing.

Classic for loop

The three parts run in order: initialise once, check the condition before each iteration, then run the increment after each iteration's body.

Range-based for loop

`for (int x : vec)` iterates directly over elements, and `for (auto& x : vec)` lets you modify elements in place via reference.

Example 1 (cpp)
for (int i = 0; i < 3; i++) {
    std::cout << i;
}
Output
012

Runs 3 times with i = 0, 1, 2.

Example 2 (cpp)
std::vector<int> v = {1, 2, 3};
for (int x : v) std::cout << x;
Output
123

Range-based for loop visits each vector element.

Key points

  • for(init; cond; inc) packs a loop into one line.
  • Range-based for iterates over containers directly.
  • auto& in a range-for allows modifying elements.
  • for loops are ideal for a known number of iterations.
๐Ÿ’ก Note: Use `for (auto& x : v)` instead of `for (auto x : v)` when you want to modify the container in place.

๐Ÿ“ Quick Quiz

1. How many parts does a classic for loop have?

2. Which loop syntax iterates directly over a container?

3. To modify elements while iterating with range-for, use: