All lessons

Loops

8 min · C#

Repeat work without writing it out a hundred times.

C# · Loops0/5 cleared

Enemy 1 of 5

The for loop

A for loop repeats a block of code a controlled number of times. The parentheses hold three parts separated by semicolons: a starting statement (run once before the loop begins), a condition (checked before every pass — the loop keeps going as long as it's true), and a step (run after each pass, usually incrementing a counter).

for (int i = 0; i < 3; i++) starts i at 0, keeps looping while i < 3, and increases i by 1 after each iteration. That produces exactly three passes, with i taking the values 0, 1, then 2 — the loop stops before i would ever reach 3.

Getting the starting value or comparison operator slightly wrong (an "off-by-one" mistake) is one of the most common bugs in any language's loops. If your output has one line too many or too few, that's the first place to look.

You
Invisible Heisenbug

Loading editor...

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