Ranges and loops in Kotlin
Ranges are values, and for iterates anything that provides one.
fun main() {
// Ranges are values: 1..5 includes both ends; downTo and step
// reshape the walk without an index variable in sight.
for (km in 1..5) print("$km ")
println()
for (switchback in 10 downTo 6) print("$switchback ")
println()
for (marker in 0..20 step 5) print("$marker ")
println()
var water = 3
while (water > 0) {
water -= 1
}
println("Bottles left: $water")
}
How it works
1..5includes both ends; the loop variable needs no declaration.10 downTo 6runs backward and0..20 step 5skips.whileis the classic guard loop for the cases ranges cannot express.
Keywords and builtins used here
forfuninmainvarwhile
The run, in numbers
- Lines
- 16
- Characters to type
- 375
- Tokens
- 90
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 77 seconds.
Step 3 of 3 in Control flow, step 6 of 27 in Language basics.