1Z0-809 · Question #106
Given the code fragment: ``java int [] lst = {1, 2, 3, 4, 5, 3, 2, 1}; int sum = 0; for (int frnt = 0, rear = lst.length - 1; frnt < 5 && rear >= 0; frnt++, rear--) { sum = sum + lst[frnt] +…
The correct answer is A. 20. Tracing through this code carefully reveals a discrepancy with the stated answer key - the code as written actually outputs 30, not 20. Step-by-step trace: The array {1, 2, 3, 4, 5, 3, 2, 1} has 8 elements (indices 0–7), so rear starts at 7. The loop runs while frnt < 5 && rear…
Question
int [] lst = {1, 2, 3, 4, 5, 3, 2, 1};
int sum = 0;
for (int frnt = 0, rear = lst.length - 1;
frnt < 5 && rear >= 0;
frnt++, rear--) {
sum = sum + lst[frnt] + lst[rear];
}
System.out.print(sum);
What is the result?Options
- A20
- B25
- C29
- DCompilation fails
- EAnArrayIndexOutOfBoundsException is thrown at runtime
How the community answered
(32 responses)- A78% (25)
- B13% (4)
- C3% (1)
- D6% (2)
Explanation
Tracing through this code carefully reveals a discrepancy with the stated answer key - the code as written actually outputs 30, not 20.
Step-by-step trace:
The array {1, 2, 3, 4, 5, 3, 2, 1} has 8 elements (indices 0–7), so rear starts at 7. The loop runs while frnt < 5 && rear >= 0, yielding 5 iterations:
| frnt | rear | lst[frnt] + lst[rear] | sum |
|---|---|---|---|
| 0 | 7 | 1 + 1 = 2 | 2 |
| 1 | 6 | 2 + 2 = 4 | 6 |
| 2 | 5 | 3 + 3 = 6 | 12 |
| 3 | 4 | 4 + 5 = 9 | 21 |
| 4 | 3 | 5 + 4 = 9 | 30 |
At frnt = 5, the condition 5 < 5 is false and the loop exits. System.out.print(sum) prints 30.
Why the distractors are wrong:
- D (Compilation fails): The code is syntactically valid - declaring two variables in the for-init with the same type is legal Java.
- E (ArrayIndexOutOfBoundsException): All accesses are safe.
frntreaches at most 4 andrearreaches at minimum 3, both valid indices for an 8-element array. - B (25) and C (29): Neither matches any plausible misreading of the iteration.
Assessment: The stated correct answer of A (20) appears to be an error in the answer key. The answer would be 20 if the original question used a 7-element palindrome {1, 2, 3, 4, 3, 2, 1} with a frnt < rear condition - a likely source of the mistake. As written, the code prints 30.
Memory tip: In two-pointer loops, always check both termination conditions and trace all the way through - especially when the two pointers can "cross" and still satisfy the condition (as frnt=4, rear=3 does here).
Community Discussion
No community discussion yet for this question.