for Loops and Ranges
Prerequisites: Operators
A loop repeats code. Kotlin's for loop runs once for each item in
something you can iterate over — a range, a list, or a string.
Ranges
fun main() {
for (i in 1..3) print("$i ")
println()
for (i in 0..<3) print("$i ")
println()
for (i in 10 downTo 6 step 2) print("$i ")
println()
for (c in 'a'..'e') print(c)
println()
}
1 2 3
0 1 2
10 8 6
abcde
1..3includes both ends.0..<3excludes the end — handy for positions, which start at 0. (0 until 3means the same thing and appears in older code.)downTocounts backwards;stepskips values.- A one-line loop body doesn't need braces, though braces are clearer for anything longer.
Looping over a collection
fun main() {
val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
println("I like $fruit")
}
for ((index, fruit) in fruits.withIndex()) {
println("${index + 1}. $fruit")
}
}
I like apple
I like banana
I like cherry
1. apple
2. banana
3. cherry
withIndex() gives each element's position too; (index, fruit)
unpacks both values.
repeat
When you just need to do something a number of times:
fun main() {
repeat(3) {
println("Hip hip hooray!")
}
}
Hip hip hooray!
Hip hip hooray!
Hip hip hooray!
Common mistakes
- Expecting
1..3to exclude 3. Use1..<3for that. - Writing a reversed range like
5..1— it's empty, so the loop never runs. Use5 downTo 1.
Practice
Print the 5 times table from 5 x 1 = 5 to 5 x 10 = 50.
Show solution
fun main() {
for (n in 1..10) {
println("5 x $n = ${5 * n}")
}
}