0
0
MATLABdata~5 mins

While loops in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While loops
O(N)
Understanding Time Complexity

We want to understand how the time a while loop takes changes as the input grows.

How many times does the loop run when input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

n = 1;
while n <= N
    disp(n);
    n = n + 1;
end

This code prints numbers from 1 up to N using a while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs repeatedly.
  • How many times: It runs once for each number from 1 to N, so N times.
How Execution Grows With Input

As N gets bigger, the loop runs more times, growing steadily.

Input Size (N)Approx. Operations
1010
100100
10001000

Pattern observation: The number of operations grows directly with N.

Final Time Complexity

Time Complexity: O(N)

This means the time grows in a straight line as the input size increases.

Common Mistake

[X] Wrong: "The while loop runs forever or a fixed number of times regardless of N."

[OK] Correct: The loop runs exactly N times because it counts from 1 to N, so it depends directly on input size.

Interview Connect

Understanding how loops grow with input helps you explain your code clearly and shows you can think about efficiency.

Self-Check

"What if we changed the loop to increase n by 2 each time? How would the time complexity change?"