0
0
Javaprogramming~5 mins

Difference between while and do–while in Java - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Difference between while and do-while
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

Both loops repeat printing and incrementing.

  • Primary operation: Printing and incrementing inside the loop.
  • How many times: Exactly n times, assuming n > 0.
How Execution Grows With Input

As n grows, the number of print operations grows roughly the same for both loops.

Input Size (n)Approx. Operations
10About 10 prints
100About 100 prints
1000About 1000 prints

Pattern observation: The work grows linearly with n for both loops.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the input size.

Common Mistake

[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.

Interview Connect

Understanding how loops grow with input helps you write efficient code and explain your choices clearly.

Self-Check

What if the loop body had a nested loop running n times inside? How would the time complexity change?