Ranges
In this page:
val range = start..end // inclusive
for (i in start until end) { } // excludes end
for (i in start downTo end) { } // descending
for (i in start..end step 2) { }
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 ..
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `range`, set to `1..5`
val range = 1..5
// Loop over `range`, binding each item to `n`
for (n in range) {
// Print "Value: $n" to the console, with a trailing newline
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
// Entry point: execution of the program starts here
fun main() {
// Loop over `0 until 5`, binding each item to `i`
for (i in 0 until 5) {
// Print "Index: $i" to the console, with a trailing newline
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
// Entry point: execution of the program starts here
fun main() {
// Loop over `5 downTo 1`, binding each item to `i`
for (i in 5 downTo 1) {
// Print "Countdown: $i" to the console, with a trailing newline
println("Countdown: $i")
}
// Print "Liftoff!" to the console, with a trailing newline
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
// Entry point: execution of the program starts here
fun main() {
// Loop over `0..10 step 2`, binding each item to `i`
for (i in 0..10 step 2) {
// Print "Even step: $i" to the console, with a trailing newline
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: