for Loops
Looping Over a Range
for (i in 1..5) iterates over the inclusive range 1 through 5, running the loop body once for each number in that sequence.
Example: Looping Over a Range
fun main() {
for (i in 1..5) {
println("Number: $i")
}
}
Login to try C/C++/Java/PHP code in the editor
Looping with until
for (i in 0 until n) loops from 0 up to, but not including, n -- the idiomatic way to repeat something exactly n times using zero-based indices.
Example: Looping with until
fun main() {
val n = 4
for (i in 0 until n) {
println("Iteration $i")
}
}
Login to try C/C++/Java/PHP code in the editor
Looping Over a Collection
A for loop can iterate directly over a List, Set, or array, giving you each element in turn without needing to track an index manually.
Example: Looping Over a Collection
fun main() {
val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
println("Fruit: $fruit")
}
}
Login to try C/C++/Java/PHP code in the editor
Looping Over a Map
Iterating a Map lets each entry be destructured directly into a key and a value inside the loop header, avoiding a separate .key/.value access.
Example: Looping Over a Map
fun main() {
val prices = mapOf("apple" to 3, "banana" to 1)
for ((fruit, price) in prices) {
println("$fruit costs $$price")
}
}
Login to try C/C++/Java/PHP code in the editor
- Trying to use a classic C-style
for (i = 0; i < 10; i++)loop; Kotlin only has thefor (x in range)style. - Iterating a
Mapand forgetting the destructuring shortcut, writing more verbose entry-based access than necessary. - Modifying a mutable list while iterating over it directly with a
forloop, which can cause aConcurrentModificationException.
- Kotlin's
forloop iterates over anything that provides an iterator: ranges, collections, arrays, and strings. for (i in 0 until n)is the idiomatic way to loop a fixed number of times without an off-by-one error.- Iterating a
Maplets you destructure each entry directly into(key, value)in the loop header. - Kotlin does not support a C-style three-part
forloop; ranges replace that use case.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: