All lessons

Loops

8 min · Scala

Repeat work without writing it out a hundred times.

Scala · Loops0/5 cleared

Enemy 1 of 5

for loops over a range

If you needed to print every number from 1 to 1000, writing 1000 separate `println` calls would be absurd. Loops let you describe the repeated work once — "print this number" — and hand control to Scala to run that description once per value in a range or collection. This is one of the most fundamental ideas in programming: repetition described declaratively instead of typed out by hand.

`for (i <- range) { ... }` walks a range of numbers, binding each one in turn to `i` and running the block. `0 until 3` produces the range 0, 1, 2 — notice that `until` is exclusive of its upper bound, so the number 3 itself is never included. This is the same zero-based, upper-bound-excluded pattern you saw with list indexing, and it's deliberate: ranges built with `until` line up neatly with valid indices into a list or array of that same length.

If you instead want both endpoints included, use `to` instead of `until` — `1 to 5` covers 1, 2, 3, 4, 5. Mixing these up (using `to` when you meant `until`, or vice versa) is one of the most common off-by-one mistakes in any language that has both, so it's worth pausing to double check which one a given loop actually needs.

You
Invisible Heisenbug

Loading editor...

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