All lessons

Loops

8 min · C++

Repeat work without writing it out a hundred times.

C++ · Loops0/5 cleared

Enemy 1 of 5

Anatomy of a for loop

A for loop repeats a block of code, and its parentheses hold three parts separated by semicolons: a starting statement (run once, before the loop begins), a condition (checked before every iteration; the loop stops as soon as this is false), and a step (run after every iteration, usually incrementing a counter).

In for (int i = 0; i < 3; i++), i starts at 0, the loop keeps going as long as i < 3, and i++ increases i by 1 after each pass through the body. That produces exactly three iterations, with i taking the values 0, 1, and 2 in turn. Notice it never actually reaches 3, since the condition is checked before that iteration would run.

A classic beginner mistake is an off-by-one error: using <= when you meant < (or the reverse), which makes the loop run one time too many or too few. Whenever a loop's output looks like it's missing the first or last item, or has one extra, check your condition first.

You
Invisible Heisenbug

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 0 1 2