← Back to Kotlin Course | Chapter 3: Control Flow | Lesson 3 of 7

for Loops

A for loop tells the computer to repeat an action once for every item in a group, like reading every name on a list out loud.

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

markup
fun main() {
    for (i in 1..5) {
        println("Number: $i")
    }
}

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

markup
fun main() {
    val n = 4
    for (i in 0 until n) {
        println("Iteration $i")
    }
}

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

markup
fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    for (fruit in fruits) {
        println("Fruit: $fruit")
    }
}

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

markup
fun main() {
    val prices = mapOf("apple" to 3, "banana" to 1)
    for ((fruit, price) in prices) {
        println("$fruit costs $$price")
    }
}
Common Mistakes
  1. Trying to use a classic C-style for (i = 0; i < 10; i++) loop; Kotlin only has the for (x in range) style.
  2. Iterating a Map and forgetting the destructuring shortcut, writing more verbose entry-based access than necessary.
  3. Modifying a mutable list while iterating over it directly with a for loop, which can cause a ConcurrentModificationException.
Chapter Summary
  • Kotlin's for loop 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 Map lets you destructure each entry directly into (key, value) in the loop header.
  • Kotlin does not support a C-style three-part for loop; ranges replace that use case.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.