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?"
Practice
enhanced for loop in Java?Solution
Step 1: Understand the enhanced for loop usage
The enhanced for loop is designed to simplify iterating over arrays or collections without manual index management.Step 2: Compare options with the loop's purpose
Only To iterate over all elements in an array or collection easily correctly describes this purpose; others describe unrelated concepts.Final Answer:
To iterate over all elements in an array or collection easily -> Option BQuick Check:
Enhanced for loop = easy iteration [OK]
- Thinking it declares variables
- Confusing with infinite loops
- Using it to replace conditional statements
nums?Solution
Step 1: Recall Java enhanced for loop syntax
The correct syntax uses: for (type variable : arrayOrCollection) { ... }Step 2: Check each option
for (int num : nums) { System.out.println(num); } matches the correct syntax. Options A, B, and C use incorrect keywords or missing parentheses.Final Answer:
for (int num : nums) { System.out.println(num); } -> Option CQuick Check:
Correct syntax uses ':' inside parentheses [OK]
- Using 'in' instead of ':'
- Omitting parentheses
- Using 'foreach' keyword in Java
int[] numbers = {1, 2, 3};
int sum = 0;
for (int n : numbers) {
sum += n;
}
System.out.println(sum);Solution
Step 1: Understand the loop operation
The loop adds each element of the array (1, 2, 3) to the variable sum.Step 2: Calculate the sum
sum = 0 + 1 + 2 + 3 = 6Final Answer:
6 -> Option AQuick Check:
Sum of 1, 2, 3 = 6 [OK]
- Concatenating numbers instead of adding
- Forgetting to initialize sum
- Syntax errors in loop
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
System.out.println(fruits);
}Solution
Step 1: Analyze the loop variable and print statement
The loop variable is 'fruit', representing each element. Printing 'fruits' prints the whole array reference each time.Step 2: Correct the print statement
To print each fruit, use 'System.out.println(fruit);' inside the loop.Final Answer:
Inside the loop, it should print 'fruit' instead of 'fruits' -> Option AQuick Check:
Print loop variable, not array name [OK]
- Printing the array variable inside the loop
- Confusing loop variable with array name
- Incorrect array declaration
List<Integer> nums = List.of(5, 12, 7, 20, 10); int count = 0; // Which code correctly counts numbers > 10?
Solution
Step 1: Understand the data and requirement
List.of(5,12,7,20,10). Numbers greater than 10: 12,20 (count=2).Step 2: Recall enhanced for loop with List<Integer>
Supports int n via automatic unboxing of Integer to int.Step 3: Check each option
A: >=10 counts 12,20,10 (3) incorrect.
B: int n >10 correct syntax, condition, count=2.
C: Missing type for n: compile error.
D: >=10 incorrect condition.Final Answer:
for (int n : nums) { if (n > 10) count++; } -> Option DQuick Check:
int n works with List<Integer> via unboxing [OK]
- Using >= instead of >
- Missing type declaration for loop variable
- Wrong comparison operator
Ready to prove it?
Pass the test and this pattern moves unknown
