All lessons

Loops

8 min · C

Repeat work without writing it out a hundred times.

C · Loops0/5 cleared

Enemy 1 of 5

How a for loop counts

A for loop repeats a block of code a controlled number of times. Its parentheses hold three parts separated by semicolons: a starting statement (run once at the very beginning), a condition (checked before each pass — the loop stops the moment it's false), and a step (run at the end of each pass, typically to move the counter forward).

In for (int i = 0; i < 3; i++), i starts at 0, the loop body keeps running while i < 3 stays true, and i++ increases i by exactly one after every iteration. That produces three passes total, with i equal to 0, then 1, then 2 — the loop stops before i ever reaches 3, because the condition is tested first.

Off-by-one mistakes (using <= where you meant <, or starting the counter at the wrong number) are extremely common with loops in every language, not just C. If your loop's output is missing the first line or has one extra at the end, check the starting value and the comparison operator first.

You
Invisible Heisenbug

Loading editor...

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