While and Do-While loops in PowerShell - Time & Space Complexity
We want to understand how the time a script takes grows when using while or do-while loops.
Specifically, how does the number of steps change as the loop runs more times?
Analyze the time complexity of the following code snippet.
$count = 0
while ($count -lt 10) {
Write-Output "Count is $count"
$count++
}
This code prints numbers from 0 to 9 using a while loop that runs until the count reaches 10.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs repeatedly.
- How many times: It runs once for each count from 0 up to 9, so 10 times.
As the number of loop runs increases, the total steps increase in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The operations grow directly with the input size; doubling input doubles work.
Time Complexity: O(n)
This means the time grows in a straight line with the number of loop runs.
[X] Wrong: "The loop runs instantly no matter how many times it repeats."
[OK] Correct: Each loop run takes time, so more runs mean more total time.
Understanding how loops affect time helps you explain your code clearly and shows you know how scripts scale.
"What if we changed the loop to run until count is less than n squared? How would the time complexity change?"