Changing the step of a range
A range goes up by 1 unless you say otherwise. To change the step, add by and the amount after the end of the range. This prints the even numbers from 2 through 10:
for (i <- 2 to 10 by 2) {
println(i)
}
The output is 2, 4, 6, 8 and 10, one per line. Read the range from left to right:
- it starts at 2;
to 10includes 10 as the last possible value;by 2adds 2 each time, so the values are 2, 4, 6, 8 and 10.
The step is applied to the start value, so the start decides which numbers you get. Starting at 2 and adding 2 can only give even numbers.
Using it with until
by works with until in the same way. The range 2 until 10 by 2 gives 2, 4, 6 and 8, because 10 is excluded. The end value does not need to be one of the values the step produces: 1 to 10 by 3 gives 1, 4, 7 and 10, and 1 to 9 by 3 gives 1, 4 and 7. The range just stops at the last value that doesn't go past the end.
The assignment: odd numbers from 7 through 23
The task is to print 7, 9, 11, and so on up to 23.
- Pick the start. The first number is 7, which is odd, so adding 2 each time will keep giving odd numbers.
- Pick the end and the kind of end. The last number, 23, must be printed, so use
to: the range is7 to 23. - Set the step. Consecutive odd numbers differ by 2, so add
by 2. The full range is7 to 23 by 2. - Print the loop variable. The body is
println(i), which puts each value on its own line.
for (i <- 7 to 23 by 2) {
println(i)
}
The output is 7, 9, 11, 13, 15, 17, 19, 21 and 23, each on its own line. That is nine numbers.
Checking the result
To see how many values a range has before looping, ask for its size: (7 to 23 by 2).size is 9. The first value is 7 and each of the other eight values adds 2, so the last one is 7 + 8 * 2 = 23, which matches the end of the range.
Common mistakes
- Forgetting
by 2.7 to 23prints every number from 7 to 23, odd and even. - Starting on the wrong parity.
8 to 23 by 2prints even numbers. The start value decides whether the results are odd or even. - Using
until 23. That leaves out 23 itself. - Using a step of 0.
7 to 23 by 0compiles, but building the range fails at run time with anIllegalArgumentExceptionsaying that the step cannot be 0. - Using a bigger step than intended.
by 3would skip some of the numbers you want, such as 9.
Key takeaways
range by stepchanges how far each step moves; the default is 1.- The start value and the step together decide which numbers appear, so odd and even sequences differ only in where they begin.
- The end of the range is a limit, not a promise that the last value will equal it.
