Certainly! In Kotlin, break
and continue
are control flow statements used within loops to alter the flow of execution.
break
StatementThe break
statement is used to terminate the loop immediately when a certain condition is met, regardless of whether the loop's condition is still true or not.
Example
fun main() {
for (i in 1..5) {
if (i == 3) {
break // Exit the loop when i is equal to 3
}
println("Number: $i")
}
}
Number: 1
Number: 2
continue
StatementThe continue
statement is used to skip the current iteration of the loop and continue with the next iteration.
Example
fun main() {
for (i in 1..5) {
if (i == 3) {
continue // Skip iteration when i is equal to 3
}
println("Number: $i")
}
}
Number: 1
Number: 2
Number: 4
Number: 5
break
and continue
statements are useful for controlling the flow of loops in Kotlin. break
terminates the loop prematurely, while continue
skips the current iteration and proceeds to the next one. These statements help you customize the behavior of loops based on specific conditions.