0
0
MATLABdata~5 mins

Break and continue in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Break and continue
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
104
1004
10004

Pattern observation: The loop stops early, so work does not grow with input size.

Final Time Complexity

Time Complexity: O(1)

This means the loop runs a fixed number of times, no matter how big the input is.

Common Mistake

[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.

Interview Connect

Understanding how break and continue affect loops helps you explain code efficiency clearly and confidently.

Self-Check

"What if we replaced break with continue? How would the time complexity change?"