Kotlin provides loop control statements like break, continue, and labels to control the flow of loops more precisely.
break StatementExits 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
continue StatementSkips 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
continue to skip specific values easily!
breakWhen 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
continueSimilarly, 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
break → exit loopcontinue → skip current iterationlabel@ → control outer loopsHelp others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!