Mastering Loops in Kotlin: The Power of Break
When working with loops, there are times when you need to exit the loop immediately, without checking the test expression. This is where the break
statement comes in – a powerful tool that terminates the nearest enclosing loop when encountered.
How Break Works
The break
statement is often used in conjunction with the if..else
construct. For instance, if a test expression evaluates to true
, the break
statement is executed, terminating the loop. Let’s take a closer look at an example:
kotlin
for (i in 1..10) {
if (i == 5) break
println(i)
}
When you run this program, the output will be:
1
2
3
4
As soon as the value of i
equals 5, the expression i == 5
inside the if
statement is evaluated to true
, and the break
statement is executed, terminating the for
loop.
Calculating Sum Until User Enters 0
Another example demonstrates how to calculate the sum of numbers entered by the user until they enter 0:
kotlin
var sum = 0
while (true) {
print("Enter a number: ")
val num = readLine()!!.toInt()
if (num == 0) break
sum += num
}
println("Sum: $sum")
In this program, the while
loop runs indefinitely until the user enters 0. When they do, the break
statement is executed, terminating the loop.
Labeled Break: Taking Control
What you’ve learned so far is the unlabeled form of break
, which terminates the nearest enclosing loop. However, there’s another way to use break
– the labeled form – which allows you to terminate a specific loop, even if it’s an outer loop.
In Kotlin, a label starts with an identifier followed by the @
symbol. By using break
with a label, you can target the desired loop. Let’s see an example:
kotlin
first@ while (true) {
second@ while (true) {
print("Enter a number: ")
val num = readLine()!!.toInt()
if (num == 2) break@first
println("You entered: $num")
}
}
When you run this program, the output will be:
Enter a number: 1
You entered: 1
Enter a number: 2
Here, when the expression i == 2
is evaluated to true
, break@first
is executed, terminating the loop marked with the label first@
.
Mastering Structural Jump Expressions
In Kotlin, there are three structural jump expressions: break
, continue
, and return
. By understanding how to use these expressions effectively, you can take your coding skills to the next level. To learn more about continue
and return
expressions, visit our resources on Kotlin continue and Kotlin functions.