break Statement in Kotlin
Deslize para mostrar o menu
What is the break Statement?
The break statement is used to stop a loop immediately. When you use break inside a loop, the loop ends right away—even if it has not finished all its iterations. After the break statement runs, your program continues with the code that comes after the loop. This is helpful when you want to exit a loop early based on a certain condition.
break in for Loops
You can use break to exit a for loop when a certain condition is met:
package com.example
fun main() {
for (i in 1..10) {
if (i == 5) {
break
}
println("Current number: $i")
}
}
This code prints numbers from 1 to 4. When i equals 5, the break statement stops the loop.
break in while Loops
You can also use break in a while loop to exit based on a condition:
package com.example
fun main() {
var count = 1
while (count <= 10) {
if (count == 5) {
break
}
println("Count: $count")
count++
}
}
This example prints numbers from 1 to 4. The loop stops as soon as count reaches 5.
Use break to make your loops more flexible and responsive to changing conditions.
Main.kt
The break statement is a powerful tool for controlling the flow of your loops. By using break, you can exit a loop as soon as a certain condition is met, rather than waiting for the loop to finish all its iterations. This allows you to write more efficient and responsive programs, especially when searching for values or handling special cases. Mastering break helps you manage complex logic and improve the overall performance of your code.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo