0
0
Javaprogramming~5 mins

While loop execution flow in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While loop execution flow
O(n)
Understanding Time Complexity

We want to understand how the time taken by a while loop changes as the input 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;
while (i < n) {
    System.out.println(i);
    i++;
}
    

This code prints numbers from 0 up to n-1 using a while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs and prints a number each time.
  • How many times: The loop 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 prints
100100 prints
10001000 prints

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

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the input size; more input means more loop runs.

Common Mistake

[X] Wrong: "The while loop runs forever or a fixed number of times regardless of n."

[OK] Correct: The loop depends on n and stops when i reaches n, so it runs exactly n times, not forever or a fixed small number.

Interview Connect

Understanding how loops grow with input size is a key skill. It helps you explain how your code will behave with bigger data, which is important in real projects.

Self-Check

"What if we changed the increment from i++ to i += 2? How would the time complexity change?"