0
0
Javaprogramming~5 mins

Why while loop is needed in Java - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why while loop is needed
O(n)
Understanding Time Complexity

We want to see how the time a program takes changes when it uses a while loop.

How does the number of steps grow as the loop runs more times?

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 repeats printing and incrementing.
  • How many times: It runs as many times as the value of n.
How Execution Grows With Input

Each time n grows, the loop runs more times, so the work grows in a straight line.

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

Pattern observation: The number of steps grows directly with n.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line as n gets bigger.

Common Mistake

[X] Wrong: "The while loop runs only once no matter what."

[OK] Correct: The loop runs as many times as the condition is true, so it depends on n.

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you know how programs grow with input.

Self-Check

"What if we changed the while loop to run until i < n*n? How would the time complexity change?"