0
0
MATLABdata~10 mins

Break and continue in MATLAB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Break and continue
Start Loop
Check Condition
Check Break?
Yes
Break Loop
Check Continue?
Yes
Skip Rest of Loop
Back to Start Loop
The loop starts and checks the condition. If false, it exits. If true, it checks if break or continue applies. Break exits loop immediately; continue skips to next iteration.
Execution Sample
MATLAB
for i = 1:5
  if i == 3
    break;
  elseif i == 2
    continue;
  end
  disp(i);
end
Loop from 1 to 5, skip printing 2, stop loop when i is 3.
Execution Table
IterationiCondition i==3?Condition i==2?ActionOutput
11FalseFalsePrint i1
22FalseTrueContinue (skip print)
33TrueFalseBreak loop
----Loop ends-
💡 Loop ends because break is triggered at i=3
Variable Tracker
VariableStartAfter 1After 2After 3Final
i-123-
Key Moments - 2 Insights
Why does the loop stop at i=3 even though the loop range is 1 to 5?
Because the break statement triggers when i equals 3, immediately exiting the loop as shown in execution_table row 3.
Why is the number 2 not printed even though the loop reaches i=2?
Because the continue statement skips the rest of the loop body for i=2, so disp(i) is not executed, as shown in execution_table row 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when i equals 2?
A2 is printed
BNothing is printed
CLoop breaks
DError occurs
💡 Hint
Check the Action and Output columns for iteration 2 in the execution_table.
At which iteration does the loop stop executing?
AAfter iteration 1
BAfter iteration 2
CAfter iteration 3
DAfter iteration 5
💡 Hint
Look at the Condition i==3? and Action columns in the execution_table.
If the break statement was removed, what would happen to the output?
AOnly 1 would print
BNumbers 1, 3, 4, 5 would print
CNumbers 1 to 5 would print except 2
DNo numbers would print
💡 Hint
Without break, loop runs full range; continue skips printing 2 as shown in variable_tracker and execution_table.
Concept Snapshot
Break and continue in MATLAB loops:
- break exits loop immediately
- continue skips current iteration rest
- Use inside if conditions
- Controls loop flow clearly
- Helps skip or stop early
Full Transcript
This example shows a MATLAB for loop from 1 to 5. When i equals 2, the continue statement skips printing i, so 2 is not shown. When i equals 3, the break statement stops the loop immediately, so the loop ends early. The execution table tracks each iteration's variable i, conditions checked, actions taken, and output. The variable tracker shows how i changes each step. Key moments clarify why the loop stops early and why 2 is not printed. The visual quiz tests understanding of these steps. The concept snapshot summarizes break and continue usage in MATLAB loops.