Range
- Kotlin course
- Beginner
- Lesson 45/116
- 5 min
Learn ranges with 1..10 and until/downTo.
Range
A range is a sequence of numbers. 1..5 contains all numbers from 1 to 5 (5 inclusive). until excludes the upper bound.
for (i in 1..5) print(i) // 12345
for (i in 1 until 5) print(i) // 1234
for (i in 5 downTo 1) print(i) // 543211..5 includes 5, 1 until 5 does not. downTo counts backward. Ranges are especially useful in for loops.
Two dots (..) make a range; both ends are inclusive.
Practice Count forward and backward
Write a fun main(). Use for (i in 1..5) { println(i) } to count 1 to 5. Then use for (i in 5 downTo 1) { println(i) } to count 5 to 1 backward. Write both loops.
Starter code
fun main() {
// Count forward and backward
}Sample solution
fun main() {
for (i in 1..5) {
println(i)
}
for (i in 5 downTo 1) {
println(i)
}
}Expected output
1 2 3 4 5 5 4 3 2 1
Step size
step sets the range's step size. The default step is 1; step 2 jumps by two each time.
for (i in 1..10 step 2) print(i) // 13579
for (i in 10 downTo 1 step 3) print(i) // 10741The first loop prints 1, 3, 5, 7, 9. The second counts down from 10 to 1 by threes: 10, 7, 4, 1.
step works with both .. and downTo; the step is always a positive integer.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the range forms
| Term | Meaning |
|---|---|
1..5 |
1,2,3,4,5 |
1 until 5 |
1,2,3,4 |
5 downTo 1 |
5,4,3,2,1 |
1..1 |
1 |
2 Complete the range with until
for (i in 1 ____ 5) { println(i) }
for (i in 1 until 5) { println(i) }
Explanation: The 1 until 5 range gives 1, 2, 3, 4 (5 excluded).
3 Which numbers does 1 until 5 contain?
- 1,2,3,4,5
- 5
- 1,2,3
- 1,2,3,4 Correct answer
Explanation: until excludes the upper bound: 1, 2, 3, 4.