Counter-based while loop in Java - Time & Space Complexity
We want to see how the time it takes to run a counter-based while loop changes as the number it counts to gets bigger.
How does the number of steps grow when the loop runs more times?
Analyze the time complexity of the following code snippet.
int count = 0;
while (count < n) {
System.out.println(count);
count++;
}
This code prints numbers from 0 up to n-1 using a while loop that increases the counter each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs and prints the current count.
- How many times: It repeats exactly n times, once for each number from 0 to n-1.
As n gets bigger, the loop runs more times, so the total steps grow in a straight line with n.
| 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: Doubling n doubles the work, so the growth is steady and linear.
Time Complexity: O(n)
This means the time to finish grows directly in proportion to the size of n.
[X] Wrong: "The loop runs a fixed number of times no matter what n is."
[OK] Correct: The loop depends on n and runs once for each number up to n, so bigger n means more steps.
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 many real tasks.
"What if we changed the loop to count down from n to 0? How would the time complexity change?"