Ranges
In this page:
Inclusive Ranges with ..
The .. operator creates a range that includes both its start and end values, commonly used directly inside for loops or in checks.
Example: Inclusive Ranges with ..
fun main() {
val range = 1..5
for (n in range) {
println("Value: $n")
}
}
Login to try C/C++/Java/PHP code in the editor
Excluding the End with until
until builds a range that excludes its upper bound, which is the idiomatic way to loop exactly n times starting from zero.
Example: Excluding the End with until
fun main() {
for (i in 0 until 5) {
println("Index: $i")
}
}
Login to try C/C++/Java/PHP code in the editor
Counting Down with downTo
downTo creates a descending range, letting a for loop count backward from a higher number to a lower one.
Example: Counting Down with downTo
fun main() {
for (i in 5 downTo 1) {
println("Countdown: $i")
}
println("Liftoff!")
}
Login to try C/C++/Java/PHP code in the editor
Custom Increments with step
Chaining .step(n) onto a range changes how much the value increases (or decreases) each iteration, letting you skip over values.
Example: Custom Increments with step
fun main() {
for (i in 0..10 step 2) {
println("Even step: $i")
}
}
Login to try C/C++/Java/PHP code in the editor
- Using
..when the upper bound should be excluded, off-by-one errors are common;until(or..<) excludes the end value. - Forgetting
downTofor counting backward; a plain..range always goes in increasing order. - Ignoring the
stepfunction when a non-1 increment is needed, and instead manually skipping values inside the loop body.
a..bcreates an inclusive range fromatob.a until b(ora..<b) creates a range that excludes the upper boundb.a downTo bcreates a descending range fromadown tob..step(n)changes the increment of any range, letting you skip values.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: