While loops in MATLAB - Time & Space 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?
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 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.
As N gets bigger, the loop runs more times, growing steadily.
| Input Size (N) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with N.
Time Complexity: O(N)
This means the time grows in a straight line as the input size increases.
[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.
Understanding how loops grow with input helps you explain your code clearly and shows you can think about efficiency.
"What if we changed the loop to increase n by 2 each time? How would the time complexity change?"