Choosing where a range starts and stops
With a for loop over a range, the two ends of the range decide which numbers appear. To print every number from 2 through 6, start the range at 2 and end it at 6 with to:
for (i <- 2 to 6) {
println(i)
}
The output is 2, 3, 4, 5 and 6, each on its own line. The range 2 to 6 starts at 2, includes 6, and goes up by 1 because that is the default step.
to versus until
Scala has two ways to write the end of a range:
| Range | Values |
|---|---|
2 to 6 | 2, 3, 4, 5, 6 |
2 until 6 | 2, 3, 4, 5 |
Use to when the end value is one of the numbers you want, and until when it is the first number you don't want. Both are ordinary methods written without dots, so 2 to 6 is the same as 2.to(6).
The assignment: print 3 through 10
The task is to print every number from 3 through 10.
- Write the loop with the right range. Both ends are wanted, so use
to:for (i <- 3 to 10). With3 until 10the loop would stop at 9. - Print the loop variable. Inside the body,
println(i)prints the current value.printlnends each output with a newline, so every number gets its own line.
for (i <- 3 to 10) {
println(i)
}
The output is 3, 4, 5, 6, 7, 8, 9 and 10, one per line.
Why a range-based loop is safe
The range is fixed before the loop starts, and the loop variable takes each of its values exactly once. There is no condition that could fail to become false, and no update line to forget. That makes this loop a good fit whenever you know the numbers you want in advance.
Notes on ranges
- An empty range is fine.
5 to 2has no values, because ranges count upward by default. The loop body simply never runs, and there is no error. Counting down needs a negative step, which later lessons cover. - The loop variable follows the range. You don't declare
ias anIntyourself. Its type comes from the range, which here is a range ofInt. - The same start and end give one value.
4 to 4runs the body once, while4 until 4runs it zero times.
Common mistakes
- Using
untilwhen the end should be included. This leaves out the last number, which is the most frequent error. - Using
towhen the end should be excluded. This prints one value too many. - Starting from the wrong number. Starting at 0 or 1 prints extra numbers before 3.
- Printing a different variable. The body must print the loop variable, here
i, or every line shows the same value.
Key takeaways
a to bincludesb;a until bexcludes it.- A range goes up by 1 unless a step is given.
- If the start is already past the end, the loop body doesn't run at all.
