Enhanced for loop in Java - Time & Space Complexity
We want to understand how the time it takes to run an enhanced for loop changes as the list size grows.
How does the number of steps grow when we loop over more items?
Analyze the time complexity of the following code snippet.
int sum = 0;
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
sum += num;
}
System.out.println(sum);
This code adds up all numbers in an array using an enhanced for loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop goes through each number in the array once.
- How many times: Exactly once for each item in the array.
As the array gets bigger, the loop runs more times, one for each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "The enhanced for loop runs faster than a regular for loop because it looks simpler."
[OK] Correct: Both loops do the same number of steps; the difference is only in how we write them, not how fast they run.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how to think about efficiency.
"What if we nested one enhanced for loop inside another over the same array? How would the time complexity change?"