In Kotlin, loops such as for
, while
, and do-while
help you execute repetitive tasks. However, there are times when you need more control over how the loop operates—perhaps you need to skip an iteration or stop the loop early. This is where break
and continue
come in. These keywords give you the ability to control the flow within loops, allowing you to exit or skip iterations based on certain conditions.
In this article, we’ll explore how break
and continue
work in Kotlin, when to use them, and how labeled versions of these keywords can provide even more control over nested loops.
1. The break
Statement
The break
statement is used to immediately exit a loop, regardless of the current iteration. Once the break
statement is encountered, the loop is terminated, and the program continues with the next statement following the loop.
Example: Using break
in a for
Loop
fun main() {
for (i in 1..10) {
if (i == 5) {
break // Exit the loop when i equals 5
}
println(i)
}
println("Loop exited.")
}
Output:
1
2
3
4
Loop exited.
In this example, the loop terminates as soon as i
equals 5
, thanks to the break
statement. Any further iterations of the loop are skipped, and the program resumes execution after the loop.
Example: Using break
in a while
Loop
fun main() {
var count = 1
while (count <= 10) {
println("Count: $count")
if (count == 6) {
break // Exit the loop when count equals 6
}
count++
}
println("Exited the while loop.")
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Exited the while loop.
In this case, the while
loop stops when count
reaches 6
, and the program continues after the loop.
2. The continue
Statement
The continue
statement is used to skip the current iteration of the loop and move on to the next one. Unlike break
, continue
does not exit the loop—it simply skips any remaining code in the current iteration and proceeds to the next iteration.
Example: Using continue
in a for
Loop
fun main() {
for (i in 1..10) {
if (i == 5) {
continue // Skip the rest of the loop when i equals 5
}
println(i)
}
}
Output:
1
2
3
4
6
7
8
9
10
Here, the continue
statement skips printing the number 5
but keeps the loop running for the remaining iterations.
Example: Using continue
in a while
Loop
fun main() {
var count = 0
while (count < 10) {
count++
if (count % 2 == 0) {
continue // Skip even numbers
}
println("Odd number: $count")
}
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
In this example, the continue
statement skips over even numbers, allowing the loop to print only odd numbers.
3. Labeled break
and continue
When dealing with nested loops, you might want to exit or skip specific loops. Kotlin provides labeled break
and labeled continue
to give you more control in these scenarios. Labels allow you to specify which loop to exit or continue, making it easier to manage nested loops.
Defining a Label
You can define a label by placing a label name followed by @
before the loop. You can then use this label with break
or continue
to control which loop should be affected.
Example: Labeled break
fun main() {
outerLoop@ for (i in 1..5) {
for (j in 1..5) {
if (i * j == 9) {
println("Breaking out of both loops")
break@outerLoop // Exit the outer loop when i * j equals 9
}
println("i = $i, j = $j")
}
}
println("Exited the outer loop.")
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 1, j = 4
i = 1, j = 5
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 2, j = 4
i = 2, j = 5
i = 3, j = 1
i = 3, j = 2
Breaking out of both loops
Exited the outer loop.
In this example, the break@outerLoop
statement terminates both the inner and outer loops when i * j == 9
, instead of just breaking out of the inner loop.
Example: Labeled continue
fun main() {
outerLoop@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) {
println("Skipping iteration of outer loop when j == 2")
continue@outerLoop // Skip the rest of the current iteration of the outer loop
}
println("i = $i, j = $j")
}
}
}
Output:
i = 1, j = 1
Skipping iteration of outer loop when j == 2
i = 2, j = 1
Skipping iteration of outer loop when j == 2
i = 3, j = 1
Skipping iteration of outer loop when j == 2
In this case, continue@outerLoop
skips the rest of the current iteration of the outer loop whenever j
equals 2
. The inner loop does not finish its iteration when j == 2
.
4. Real-World Use Case: Finding a Number in a Matrix
Let’s use break
and continue
in a practical scenario. Suppose we need to find the first occurrence of a specific number in a 2D array (matrix) and stop the search as soon as we find it.
Example:
fun main() {
val matrix = arrayOf(
intArrayOf(1, 2, 3),
intArrayOf(4, 5, 6),
intArrayOf(7, 8, 9)
)
val target = 5
outerLoop@ for (i in matrix.indices) {
for (j in matrix[i].indices) {
if (matrix[i][j] == target) {
println("Found $target at position [$i][$j]")
break@outerLoop // Exit both loops once the target is found
}
}
}
}
Output:
Found 5 at position [1][1]
Here, the break@outerLoop
ensures that the search stops as soon as the target is found, exiting both loops immediately.
Conclusion
The break
and continue
statements in Kotlin give you powerful control over loop execution, allowing you to exit loops early or skip iterations. When working with nested loops, labeled break
and labeled continue
provide even more control, letting you specify exactly which loop to affect.
break
: Use this to exit a loop early.continue
: Use this to skip the current iteration and move to the next one.- Labeled
break
andcontinue
: These give you the ability to control nested loops by specifying which loop to break or continue.
Next up, we’ll dive into flow control using return
, break
, and continue
in higher-order functions in Kotlin. You’ll learn how to use these keywords to control the flow within functions that take lambdas. Stay tuned!