While loop in Swift - Time & Space Complexity
We want to understand how the time a while loop takes changes as the input grows.
Specifically, how many times does the loop run when the input gets bigger?
Analyze the time complexity of the following code snippet.
var count = 0
let n = 100
while count < n {
print(count)
count += 1
}
This code prints numbers from 0 up to n-1 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 0 to n-1, so n times.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times |
| 100 | About 100 times |
| 1000 | About 1000 times |
Pattern observation: The operations increase directly with n; if n doubles, operations double.
Time Complexity: O(n)
This means the time grows in a straight line with the input size.
[X] Wrong: "The while loop runs a fixed number of times no matter the input."
[OK] Correct: The loop runs as many times as n, so bigger n means more runs.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how to write efficient programs.
"What if we changed the loop to count down from n to 0? How would the time complexity change?"