Difference between while and do–while in Java - Performance Comparison
We want to see how the time it takes to run loops changes with input size.
Specifically, we compare two loop types: while and do-while.
Analyze the time complexity of these two loops.
int i = 0;
while (i < n) {
System.out.println(i);
i++;
}
int j = 0;
do {
System.out.println(j);
j++;
} while (j < n);
Both loops print numbers from 0 up to n-1, but the order of checking the condition differs.
Both loops repeat printing and incrementing.
- Primary operation: Printing and incrementing inside the loop.
- How many times: Exactly n times, assuming n > 0.
As n grows, the number of print operations grows roughly the same for both loops.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prints |
| 100 | About 100 prints |
| 1000 | About 1000 prints |
Pattern observation: The work grows linearly with n for both loops.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the input size.
[X] Wrong: "do-while loops always run slower because they run the loop body before checking the condition."
[OK] Correct: Both loops run the body about n times, so their time grows the same way; the difference is only when the condition is checked.
Understanding how loops grow with input helps you write efficient code and explain your choices clearly.
What if the loop body had a nested loop running n times inside? How would the time complexity change?