0
0
Kotlinprogramming~10 mins

Break and continue behavior in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Break and continue behavior
Start loop
Check condition
Yes
Inside loop body
If 'continue' condition?
YesSkip rest, next iteration
If 'break' condition?
YesExit loop
Execute remaining code
Next iteration
Condition false
Exit loop
The loop starts and checks its condition. Inside, if 'continue' is met, it skips to the next iteration. If 'break' is met, it exits the loop immediately. Otherwise, it runs the rest of the loop body.
Execution Sample
Kotlin
for (i in 1..5) {
    if (i == 3) continue
    if (i == 4) break
    println(i)
}
This loop prints numbers 1 to 5 but skips 3 and stops completely at 4.
Execution Table
IterationiCondition i==3ActionCondition i==4ActionOutput
11falseNo continuefalseNo breakPrint 1
22falseNo continuefalseNo breakPrint 2
33trueContinue (skip print)N/AN/A
44falseNo continuetrueBreak (exit loop)
------Loop ends
💡 At iteration 4, break condition is true, so loop exits immediately.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
i-1234-
Key Moments - 2 Insights
Why does the number 3 not get printed even though the loop reaches it?
Because at iteration 3, the 'continue' condition is true (i == 3), so the loop skips the print statement and moves to the next iteration, as shown in row 3 of the execution_table.
Why does the loop stop completely at number 4?
At iteration 4, the 'break' condition is true (i == 4), so the loop exits immediately without printing 4 or continuing further, as shown in row 4 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'i' when the loop skips printing?
A2
B3
C4
D1
💡 Hint
Check the row where 'Action' says 'Continue (skip print)' in the execution_table.
At which iteration does the loop exit due to 'break'?
A4
B3
C2
D5
💡 Hint
Look for the row where 'Action' says 'Break (exit loop)' in the execution_table.
If we remove the 'continue' statement, what will be printed at iteration 3?
ANothing, loop skips iteration 3
BLoop will break at 3
C3 will be printed
DError occurs
💡 Hint
Refer to the variable_tracker and execution_table to see what happens when 'continue' is not triggered.
Concept Snapshot
Kotlin 'break' exits the loop immediately.
'continue' skips the rest of the current iteration.
Use 'break' to stop looping early.
Use 'continue' to skip specific steps.
Both control loop flow inside loops.
Full Transcript
This example shows a Kotlin for-loop from 1 to 5. At each iteration, it checks if the current number is 3 or 4. If it is 3, the loop uses 'continue' to skip printing and moves to the next number. If it is 4, the loop uses 'break' to stop completely. The output prints 1 and 2 only. The variable 'i' changes each iteration from 1 to 4, then the loop ends. This teaches how 'break' and 'continue' control loop behavior by skipping or stopping iterations.