0
0
Javaprogramming~5 mins

Enhanced for loop in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Enhanced for loop
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array gets bigger, the loop runs more times, one for each item.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The number of steps grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the list gets bigger.

Common Mistake

[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.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how to think about efficiency.

Self-Check

"What if we nested one enhanced for loop inside another over the same array? How would the time complexity change?"