Break and continue in MATLAB - Time & Space Complexity
When we use break and continue in loops, it changes how many times the loop runs.
We want to see how these commands affect the total work done as the input grows.
Analyze the time complexity of the following code snippet.
for i = 1:n
if i == 5
break;
end
disp(i);
end
This code prints numbers from 1 up to 4, then stops the loop early using break.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from 1 to n.
- How many times: Normally n times, but break stops it early at i == 5.
Because break stops the loop at 5, the number of operations stays the same no matter how big n gets.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 4 |
| 100 | 4 |
| 1000 | 4 |
Pattern observation: The loop stops early, so work does not grow with input size.
Time Complexity: O(1)
This means the loop runs a fixed number of times, no matter how big the input is.
[X] Wrong: "The loop always runs n times even with break."
[OK] Correct: Break stops the loop early, so it can run fewer times than n.
Understanding how break and continue affect loops helps you explain code efficiency clearly and confidently.
"What if we replaced break with continue? How would the time complexity change?"