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 endedWhen 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
// 3This 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
MediumWrite 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground