A developer writes a loop to iterate over an array of integers. The loop must sum all elements and stop early if the sum exceeds 100. Which control flow construct should be used?
Trap 1: while(true) { sum += arr[i]; i++; }
Incorrect because the while(true) loop lacks a termination condition, causing an infinite loop. It also does not prevent array index out of bounds.
Trap 2: do { sum += arr[i]; i++; } while(i<arr.length && sum <= 100);
Incorrect because the do-while loop checks the condition after executing the body, so if the sum exceeds 100 during the loop, it will still add the next element before checking the condition.
- A
while(true) { sum += arr[i]; i++; }
Why wrong: Incorrect because the while(true) loop lacks a termination condition, causing an infinite loop. It also does not prevent array index out of bounds.
- B
for(int i=0; i<arr.length; i++) { sum += arr[i]; if(sum > 100) break; }
Correct. It uses a standard for loop with an index, sums each element, and breaks when sum exceeds 100.
- C
do { sum += arr[i]; i++; } while(i<arr.length && sum <= 100);
Why wrong: Incorrect because the do-while loop checks the condition after executing the body, so if the sum exceeds 100 during the loop, it will still add the next element before checking the condition.
- D
for(int val : arr) { sum += val; if(sum > 100) break; }
Correct. The enhanced for loop iterates over each element. The break statement works inside it, stopping early when sum exceeds 100.