break and continue
Prerequisites: while and do-while loops
Two keywords change how a loop runs:
breakstops the loop completely.continueskips the rest of the current pass and moves on to the next one.
Example
fun main() {
for (n in 1..10) {
if (n % 2 == 0) continue
if (n > 7) break
println(n)
}
}
Expected output
1
3
5
7
Even numbers are skipped by continue. At 9, break ends the loop.
Breaking out of nested loops
A label (a name followed by @) lets break exit an outer loop:
fun main() {
val grid = listOf(listOf(1, 2), listOf(3, 42), listOf(5, 6))
search@ for (row in grid) {
for (value in row) {
if (value == 42) {
println("Found 42")
break@search
}
}
}
}
Found 42
Labels are rarely needed — often, moving the search into a function and
using return is clearer.
Practice
Print the numbers from 1 to 20, skipping multiples of 3, and stop completely at 16.
Show solution
fun main() {
for (n in 1..20) {
if (n == 16) break
if (n % 3 == 0) continue
println(n)
}
}