Menu
Coddy logo textTech

Break

Part of the Fundamentals section of Coddy's Swift journey — lesson 45 of 86.

Sometimes you need to exit a loop early, before it finishes all its iterations. The break statement immediately stops the loop and continues with the code after it.

for number in 1...10 {
    if number == 5 {
        break
    }
    print(number)
}
// Output: 1, 2, 3, 4

When number reaches 5, the break statement executes and the loop stops completely. Notice that 5 itself is never printed because break exits before reaching the print statement.

The break statement works with all loop types. Here's an example with a while loop that searches for a specific value:

var count = 0

while true {
    count += 1
    if count == 3 {
        break
    }
}
print(count)  // Output: 3

This pattern is useful when you're searching for something and want to stop as soon as you find it, rather than continuing through unnecessary iterations.

challenge icon

Challenge

Easy
Write a function findFirstMultiple that takes limit and divisor and returns the first number (starting from 1) that is divisible by the divisor.

Use a loop to iterate through numbers starting from 1 up to the limit. When you find a number divisible by the divisor, use break to exit the loop immediately and return that number.

Logic:

  • Loop through numbers from 1 to limit
  • Check if the current number is divisible by divisor (remainder is 0)
  • If found, break out of the loop and return that number
  • If no multiple is found within the limit, return -1

Parameters:

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

Returns: The first number divisible by the divisor, or -1 if none found (Int)

For example, if limit is 10 and divisor is 3, the function returns 3 (the first number divisible by 3).

Cheat sheet

The break statement immediately stops a loop and continues with the code after it:

for number in 1...10 {
    if number == 5 {
        break
    }
    print(number)
}
// Output: 1, 2, 3, 4

When break executes, the loop stops completely. The value that triggers the break is not processed by subsequent statements in the loop.

The break statement works with all loop types, including while loops:

var count = 0

while true {
    count += 1
    if count == 3 {
        break
    }
}
print(count)  // Output: 3

This pattern is useful for searching and stopping as soon as a condition is met, avoiding unnecessary iterations.

Try it yourself

func 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