Do–while loop in Javascript - Time & Space Complexity
We want to understand how the time it takes to run a do-while loop changes as the input size grows.
Specifically, how many times the loop runs affects the total work done.
Analyze the time complexity of the following code snippet.
let i = 0;
do {
console.log(i);
i++;
} while (i < n);
This code prints numbers from 0 up to n-1 using a do-while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The do-while loop runs the block inside repeatedly.
- How many times: It runs exactly n times, once for each number from 0 to n-1.
As n grows, the number of times the loop runs grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows in a straight line with the input size.
Time Complexity: O(n)
This means the time to run the loop grows directly in proportion to the input size n.
[X] Wrong: "The do-while loop always runs at least once, so its time is constant regardless of n."
[OK] Correct: While the loop runs at least once, the total number of runs depends on n, so time grows with n.
Understanding how loops like do-while scale helps you explain how your code handles bigger inputs clearly and confidently.
"What if the loop condition was based on a fixed number instead of n? How would the time complexity change?"