Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Loops  ›  Lesson

Ranges: Counting Without a List

Range 12 minA Range such as 1 to 5 or 0 until n describes evenly spaced whole numbers by start, end and step, so you can loop over counts without building a list.

Ranges: Counting Without a List

The track coach wants to call out every lap: "Lap 1", "Lap 2", all the way to 12. There is no list of laps to loop over, only a count. A Range turns a count into something a for can walk.

The rule

to includes the end, until stops before it, by sets the step.

1 to 5           // 1, 2, 3, 4, 5
1 until 5        // 1, 2, 3, 4
0 to 20 by 5     // 0, 5, 10, 15, 20
10 to 1 by -3    // 10, 7, 4, 1
5 to 1           // empty: the default step is +1
  • A Range stores only three numbers: start, end and step. 1 to 1_000_000 takes no more memory than 1 to 5, because the numbers are worked out as you walk them.
  • It behaves like an immutable sequence: (1 to 5).sum is 15, and (1 until 5).toList is List(1, 2, 3, 4).
  • To count down, give a negative step. Without one, a Range whose start is above its end is simply empty, and a loop over it silently does nothing.

Ranges pair naturally with for:

for lap <- 1 to 12 do
  println(s"Lap $lap")

They also pair with positions in a sequence. Positions run from 0 to length − 1, so use until, or let the collection supply them with indices:

for i <- 0 until runs.length do println(s"Run ${i + 1}: ${runs(i)} km")
for i <- runs.indices do println(runs(i))   // the same positions

The shortcut

Think "counting laps" or "counting positions"? Things people number from 1, such as laps, weeks or runners, use 1 to n. Positions in a collection start at 0, so they use 0 until n, or indices. The word tells you which end to trust.

Walking positions without falling off the endStep 1 of 4
  1. The collection

    runs has 4 elements, at positions 0, 1, 2 and 3.

Drills

Answer fast — trust the rule.

quick drill

What is (1 until 5).toList?

quick drill

How many numbers are in 0 to 20 by 5?

quick drill

What is (10 to 1 by -3).toList?

quick drill

What does for i <- 5 to 1 do println(i) print?

quick drill

runs has 4 elements. What does for i <- 0 to runs.length do println(runs(i)) do?

Remember

  • to includes the end, until stops before it, and by sets the step, negative to count down.
  • Laps and weeks count from 1 with to; positions count from 0 with until or indices.
  • Trap: 0 to length runs off the end, and a downward range without a negative step is empty.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainLaps or positions?

Write two loops: one that calls out Lap 1 to Lap 12, and one that prints every element of runs by position. Explain why they use different ranges, and what goes wrong with 0 to runs.length.