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

bookbreak Statement in Kotlin

Swipe to show 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

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?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 2

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

SectionΒ 3. ChapterΒ 2
some-alt