Do–while loop in Java - Time & Space Complexity
We want to understand how the time it takes to run a do-while loop changes as the input size grows.
How many times does the loop run when the input gets bigger?
Analyze the time complexity of the following code snippet.
int i = 0;
do {
System.out.println(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 print statement 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 the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The operations increase directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the loop grows in a straight line with the size of n.
[X] Wrong: "The do-while loop always runs only once, so time is constant."
[OK] Correct: The loop runs at least once, but if n is bigger, it runs many times, so time grows with n.
Understanding how loops like do-while grow with input size helps you explain code efficiency clearly and confidently.
"What if we changed the loop to stop when i <= n instead of i < n? How would the time complexity change?"