KOTLIN Tutorial



LOOP CONTROL IN KOTLIN


Loop Control in Kotlin

Kotlin provides loop control statements like break, continue, and labels to control the flow of loops more precisely.


1. break Statement

Exits the loop immediately when a condition is met.

fun main() {
    for (i in 1..10) {
        if (i == 5) break
        print("$i ")
    }
}
  

Output: 1 2 3 4


2. continue Statement

Skips the current iteration and moves to the next one.

fun main() {
    for (i in 1..5) {
        if (i == 3) continue
        print("$i ")
    }
}
  

Output: 1 2 4 5

✅ Use continue to skip specific values easily!

3. Labeled break

When dealing with nested loops, you can break a specific outer loop using labels.

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

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
  

4. Labeled continue

Similarly, you can skip to the next iteration of an outer loop using a label.

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

Output:

i = 1, j = 1
i = 2, j = 1
i = 3, j = 1
  

🔥 Quick Summary

  • break → exit loop
  • continue → skip current iteration
  • label@ → control outer loops
💡 Tip: Use labels only when absolutely necessary — avoid overcomplicating loops.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review