0
0
Javaprogramming~5 mins

Do–while loop in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Do-while loop
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The operations increase directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the loop grows in a straight line with the size of n.

Common Mistake

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

Interview Connect

Understanding how loops like do-while grow with input size helps you explain code efficiency clearly and confidently.

Self-Check

"What if we changed the loop to stop when i <= n instead of i < n? How would the time complexity change?"