Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele break Statement in Kotlin | Advanced Loop Techniques
Kotlin Loops

bookbreak Statement in Kotlin

Pyyhkäise näyttääksesi valikon

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

Main.kt

copy

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.

question mark

What does the break statement do in a loop?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 2

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 3. Luku 2
some-alt