For loop syntax in Java - Time & Space Complexity
We want to see how the time a for loop takes changes as we increase the number of times it runs.
How does the work grow when the loop runs more times?
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
System.out.println(i);
}
This code prints numbers from 0 up to n-1, running the loop n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and prints a number each time.
- How many times: Exactly n times, where n is the input size.
As n grows, the number of print operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time grows in a straight line with the number of loop runs.
[X] Wrong: "The loop runs faster because it just prints numbers quickly."
[OK] Correct: The speed of printing doesn't change how many times the loop runs; the number of steps still grows with n.
Understanding how loops grow with input size helps you explain how your code will behave with bigger data, a key skill in programming.
"What if we added a nested loop inside this for loop? How would the time complexity change?"