In this tutorial, you shall learn how the Kotlin for loop works, how to iterate over ranges and collections, and how to use indexes, steps, descending ranges, break, and continue with practical examples.

Kotlin For Loop

A Kotlin for loop repeats a block of code for every value produced by an iterator. You can use it with lists, arrays, strings, ranges, maps, sets, and other objects that provide an iterator() function.

Unlike the traditional C-style loop, Kotlin does not use the form for (initialization; condition; update). Numeric loops are normally written with ranges such as 1..5, 1 until 5, or 10 downTo 1.

Kotlin For Loop Syntax

The syntax of a Kotlin for loop is:

</>
Copy
for (element in iterable) {
  // statement(s)
}

For each element in the iterable, the loop assigns that value to element and executes the statements inside the loop body. The loop stops after the final element has been processed, unless a break, return, or exception ends it earlier.

Kotlin For Loop Examples

1. Iterate over a List using Kotlin For Loop

In this example, we shall take a Kotlin List, and use use for loop to iterate over the elements of the list. It is kind of similar to enhanced for loop in Java.

Main.kt

</>
Copy
/**
 * Kotlin For Loop Example
 */
fun main(args: Array<String>) {
    var nums = listOf(25, 54, 68, 72)
    for(num in nums){
        println(num)
    }
}

During each iteration of the for loop, num has the next element of the list nums. So, during first iteration, num has the value of 25. In the second iteration, num has the value of 54. The iterations continue until it executes for the last element in the list.

Run the Kotlin program in IntelliJ IDE or some other IDE of your favorite. You shall get the something similar to the following printed to the console.

Output

25
54
68
72

2. Iterate over an Inclusive Kotlin Range

The following Kotlin program demonstrates how to use a for loop to execute a set of statements for each of the element in the range.

In this example, we have a range 25..31. Meaning, the range has elements from 25 to 31 in steps of 1, which is of course the default, as we have not mentioned any step value for the range.

Main.kt

</>
Copy
/**
 * Kotlin For Loop Example
 */
fun main(args: Array<String>) {
    for(num in 25..31){
        println(num)
    }
}

Run the program.

Output

25
26
27
28
29
30
31

The .. operator creates a closed range, so both 25 and 31 are included.

3. Iterate over a Kotlin Range with step

In this example, we use for loop to iterate over a range of elements. The range we take has a step value of 2.

Main.kt

</>
Copy
/**
 * Kotlin For Loop Example
 */
fun main(args: Array<String>) {
    for(num in 25..35 step 2){
        println(num)
    }
}

Run the above Kotlin program and you shall see the for loop executed for the range of elements in steps of specified step value.

Output

25
27
29
31
33
35

The step 2 modifier advances the loop value by two on every iteration. The step value must be positive.

4. Access the Index and Element with withIndex()

You can also access the index of element, along with the element, of the list. For the list, you should mention List.withIndex() similar to what we have mentioned nums.withIndex().

During each iteration, you shall get the pair (index, element).

Main.kt

</>
Copy
/**
 * Kotlin For Loop Example
 */
fun main(args: Array<String>) {
    var nums = listOf(25, 54, 68, 72)
    for((index,num) in nums.withIndex()){
        println(index.toString()+" - "+num)
    }
}

Run the above Kotlin For Loop program.

Output

0 - 25
1 - 54
2 - 68
3 - 72

The index starts at 0. Destructuring in for ((index, num) in nums.withIndex()) places the index in index and the matching list value in num.

5. Iterate over Characters in a Kotlin String

String is a collection of characters. We can iterate over the characters of the String.

In this example, we execute a set of statements for each character in a String using for loop.

Main.kt

</>
Copy
/**
 * Kotlin For Loop Example
 */
fun main(args: Array<String>) {
    var str = "kotlin"
    for(char in str){
        println(char)
    }
}

Run the Kotlin program and we shall get the following output.

Output

k
o
t
l
i
n

6. Iterate over a Kotlin Map

Map is a collection of key-value pairs. In this example, we shall write a for loop that iterates over each key-value pair of the map and executes a set of statements.

Main.kt

</>
Copy
/**
 * Kotlin For Loop Example
 */
fun main(args: Array<String>) {
    var map = mapOf(6 to "Kotlin", 7 to "Android", 4 to "Java")
    for(key in map.keys){
        println(key.toString()+" - "+map[key])
    }
}

Run the above Kotlin program.

Output

6 - Kotlin
7 - Android
4 - Java

The map created by mapOf() preserves its iteration order in this example. When order is part of your program’s behavior, use a map implementation with a documented iteration order rather than assuming that every map type behaves the same way.

7. Iterate over Map Keys and Values with Destructuring

Kotlin can destructure each map entry directly into a key and value. This avoids performing a separate lookup such as map[key].

Main.kt

</>
Copy
fun main() {
    val courses = mapOf(
        6 to "Kotlin",
        7 to "Android",
        4 to "Java"
    )

    for ((key, value) in courses) {
        println("$key - $value")
    }
}

Output

6 - Kotlin
7 - Android
4 - Java

Kotlin Range Variants for For Loops

Kotlin provides several range forms for common numeric loop requirements:

  • start..end includes both endpoints.
  • start until end excludes the ending value.
  • start..<end is another way to create an open-ended range where supported by the Kotlin version used by your project.
  • start downTo end counts downward.
  • step n changes the amount added or subtracted on each iteration.

Loop from Zero up to, but not including, a Limit

Use until when the upper bound must be excluded. This is useful for zero-based index loops.

</>
Copy
fun main() {
    for (index in 0 until 4) {
        println(index)
    }
}

Output

0
1
2
3

Count Down with downTo

Use downTo for a descending progression. A normal range such as 5..1 is empty and does not count backward.

</>
Copy
fun main() {
    for (number in 5 downTo 1) {
        println(number)
    }
}

Output

5
4
3
2
1

Using indices and lastIndex in Kotlin For Loops

When you only need valid positions, use the collection’s indices property. Use lastIndex when you need the final valid index. These properties make the loop adapt automatically when the collection size changes.

</>
Copy
fun main() {
    val names = listOf("Asha", "Ben", "Chen")

    for (index in names.indices) {
        println("$index: ${names[index]}")
    }

    println("Last index: ${names.lastIndex}")
}

Output

0: Asha
1: Ben
2: Chen
Last index: 2

Control Kotlin For Loop Execution with break and continue

Use break to stop the nearest loop immediately. Use continue to skip the remaining statements in the current iteration and proceed with the next value.

</>
Copy
fun main() {
    for (number in 1..10) {
        if (number == 3) {
            continue
        }

        if (number == 7) {
            break
        }

        println(number)
    }
}

Output

1
2
4
5
6

The loop skips 3 because of continue. It ends before printing 7 because of break.

Kotlin For Loop with Nested Loops and Labels

In nested loops, an unlabeled break affects only the innermost loop. Add a label when you need to stop an outer loop directly.

</>
Copy
fun main() {
    outer@ for (row in 1..3) {
        for (column in 1..3) {
            if (row == 2 && column == 2) {
                break@outer
            }
            println("$row, $column")
        }
    }
}

Output

1, 1
1, 2
1, 3
2, 1

When to Use for, forEach, and while in Kotlin

Use a for loop when the code should clearly express iteration over a range or collection, especially when you need break, continue, labels, or straightforward imperative logic.

Use collection operations such as map, filter, and fold when you are transforming or combining values. Use forEach for a simple action on every element, but remember that break and continue are loop statements and cannot be used inside a regular forEach lambda in the same way.

Use a while loop when repetition depends on a condition rather than on consuming all values from an iterable.

Common Kotlin For Loop Mistakes

  • Using 1..size to index a collection. Valid indexes normally run from 0 through size - 1; prefer indices.
  • Expecting 5..1 to count backward. Use 5 downTo 1.
  • Using .. when the upper value must be excluded. Use until or an open-ended range.
  • Modifying a collection structurally while iterating over it, which can produce errors or unexpected behavior. Create a filtered result or use an appropriate iterator.
  • Assuming every map implementation has the same iteration order.

Kotlin For Loop FAQs

Does Kotlin support the C-style for loop?

No. Kotlin does not support for (i = 0; i < n; i++). Use a range such as for (i in 0 until n), use indices for valid collection indexes, or use a while loop when initialization and updates must be controlled manually.

How do I get both the index and value in a Kotlin for loop?

Use withIndex(): for ((index, value) in items.withIndex()). Use items.indices when you need only indexes.

What is the difference between .. and until in Kotlin?

1..5 includes 5, while 1 until 5 stops at 4. Choose until for an exclusive upper bound.

How do I write a descending Kotlin for loop?

Use downTo, for example for (i in 10 downTo 1). Add step when needed, such as 10 downTo 2 step 2.

Kotlin For Loop Summary

In this Kotlin Tutorial, we learned how to use a Kotlin for loop with lists, strings, maps, ranges, indexes, steps, and descending progressions. We also used break, continue, and labels to control loop execution. For collection transformations, consider Kotlin collection operations; for condition-controlled repetition, use a while loop.