Kotlin Loops

for Loop (Range)

Basic Structure:

for (condition) {
    // code block
}

Example:

Loading...
Output:

This prints numbers 1 through 5 using a range.

for with step and downTo

for (i in 1..10 step 2) {
    println(i) // 1, 3, 5, 7, 9
}

for (i in 5 downTo 1) {
    println(i) // 5, 4, 3, 2, 1
}

Iterating over Collections

val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
    println(fruit)
}

while Loop

A while loop repeats a block of code as long as a condition is true. The condition is checked before each iteration, so if the condition is false at the start, the loop may not run at all.

Basic Structure

Here is this general structure of a while loop in a kotlin program.

while (condition) {
    // code block
}

Example

Loading...
Output:

do-while Loop

A do-while loop always runs the code block at least once, because the condition is checked after the block executes.

Basic Structure

do {
    // code block
} while (condition)
Loading...
Output:

break and continue

break exits a loop. continue skips the current iteration.

for (i in 1..5) {
    if (i == 3) continue
    if (i == 5) break
    println(i)
}

This prints: 1, 2, 4

Labeled Loops

Kotlin allows breaking from nested loops using labels:

outer@ for (i in 1..3) {
    for (j in 1..3) {
        if (i == 2 && j == 2) break@outer
        println("i=$i, j=$j")
    }
}

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic