Break and Continue in Kotlin

1. Why use Break and Continue?

In Kotlin, loops are often used to repeat actions, but sometimes you need more control over their flow. The break and continue statements help you manage that control:

These statements improve readability and efficiency by preventing unnecessary iterations once a goal is reached or a condition is satisfied.


2. How to Use (with Examples)

Example 1: Using break

fun main() {
    for (i in 1..10) {
        if (i == 5) {
            println("Stopping loop at $i")
            break
        }
        println("Number: $i")
    }
}
    

Explanation: The loop stops as soon as i becomes 5. Any numbers after 5 are not printed.

Example 2: Using continue

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

Explanation: When i equals 3, that iteration is skipped. The loop continues from the next value.

Example 3: Labeled Loops with break

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")
        }
    }
}
    

Explanation: The break@outer statement stops not only the inner loop but also the outer one. Labels are useful when working with nested loops.


3. When to Use and When Not to Use

Use when:
Avoid when:

4. Interview Questions