Why while loop is needed in Java - Performance Analysis
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?
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 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.
Each time n grows, the loop runs more times, so the work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prints and increments |
| 100 | About 100 prints and increments |
| 1000 | About 1000 prints and increments |
Pattern observation: The number of steps grows directly with n.
Time Complexity: O(n)
This means the time grows in a straight line as n gets bigger.
[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.
Understanding how loops affect time helps you explain your code clearly and shows you know how programs grow with input.
"What if we changed the while loop to run until i < n*n? How would the time complexity change?"