Menu
Coddy logo textTech

Break

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 49 of 93.

Sometimes you need to exit a loop early, before it naturally finishes. The break statement lets you immediately stop a loop and jump to the code after it.

Consider searching for a specific number in a range:

for (i in 1..10) {
    if (i == 5) {
        println("Found it!")
        break
    }
    println(i)
}
println("Loop ended")
// Output:
// 1
// 2
// 3
// 4
// Found it!
// Loop ended

When i equals 5, the break executes and the loop stops immediately. The remaining iterations (6 through 10) never run.

The break statement works with all loop types.

Here's an example with a while loop:

var count = 0
while (true) {
    count++
    if (count > 3) {
        break
    }
    println(count)
}
// Output:
// 1
// 2
// 3

This pattern is useful when you want to exit based on a condition that's easier to check inside the loop rather than in the loop's condition itself.

challenge icon

Challenge

Medium

Write a function findFirstMultiple that takes limit and divisor and returns the first number in the range from 1 to limit that is divisible by divisor.

Use a loop with break to stop searching as soon as you find a match.

Parameters:

  • limit (Int): The upper bound of the search range (inclusive)
  • divisor (Int): The number to check divisibility against

Returns: The first number divisible by divisor, or -1 if no such number exists in the range.

Input constraints: The limit and divisor are positive integers.

Try it yourself

fun findFirstMultiple(limit: Int, divisor: Int): Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground