Loops
8 min · C#
Repeat work without writing it out a hundred times.
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.
Stuck? Ask Rena
Your AI tutor that gives assistance.
Asking Rena in lessons is on Ultimate.