Loops
8 min · C#
Repeat work without writing it out a hundred times.
Enemy 1 of 5
The for loop
This for loop starts i at 0 and repeats while i is less than 3, adding 1 each pass. It prints each value of i. Press Run to see 0, 1, 2.
Why this works
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.