while loop in Bash Scripting - Time & Space Complexity
We want to understand how the time a while loop takes changes as the input size grows.
Specifically, how many times does the loop run when input gets bigger?
Analyze the time complexity of the following code snippet.
count=0
limit=100
while [ $count -lt $limit ]
do
echo "Count is $count"
((count++))
done
This code prints numbers from 0 up to one less than the limit using a while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs the echo and increment commands repeatedly.
- How many times: It runs once for each number from 0 up to limit minus one, so limit times.
As the limit grows, the number of loop runs grows the same way.
| Input Size (limit) | Approx. Operations (loop runs) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time taken grows in a straight line as the input size increases.
[X] Wrong: "The while loop runs a fixed number of times no matter the input."
[OK] Correct: The loop count depends on the limit variable, so if limit grows, the loop runs more times.
Understanding how loops grow with input helps you explain script performance clearly and confidently.
"What if we changed the increment from 1 to 2 each time? How would the time complexity change?"