While loop execution flow in Java - Time & Space 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?
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 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.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The operations increase directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time grows in a straight line with the input size; more input means more loop runs.
[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.
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.
"What if we changed the increment from i++ to i += 2? How would the time complexity change?"