1Z0-808 · Question #49
QUESTION 60 Given the code fragment: int a[] = {1, 2, 3, 4, 5}; for (XXXX) { System.out.print (a[e]); } Which option can replace xxxx to enable the code to print 135?
The correct answer is B. int e=0; e<5; e+=2. Option B (int e=0; e<5; e+=2) starts at index 0 and increments by 2 each iteration, producing indices 0, 2, and 4 - which map to array values 1, 3, and 5 respectively, exactly the desired output. Why the distractors fail: A (e++) increments by 1, visiting every index (0–4) and…
Question
Options
- Aint e=0; e<=4; e++
- Bint e=0; e<5; e+=2
- Cint e=0; e<=5; e+=1
- Dint e=1; e<=5; e+=2
How the community answered
(40 responses)- A5% (2)
- B78% (31)
- C13% (5)
- D5% (2)
Explanation
Option B (int e=0; e<5; e+=2) starts at index 0 and increments by 2 each iteration, producing indices 0, 2, and 4 - which map to array values 1, 3, and 5 respectively, exactly the desired output.
Why the distractors fail:
- A (
e++) increments by 1, visiting every index (0–4) and printing all five values: 1 2 3 4 5. - C (
e<=5) has the same step-by-1 problem as A, and also goes out of bounds at index 5, throwing anArrayIndexOutOfBoundsException. - D starts at
e=1(value 2, not 1), skips the first element, and also throws anArrayIndexOutOfBoundsExceptionwhenereaches 5.
Memory tip: To print every other element starting from the first, remember the pattern: start at 0, step by 2, stop before the length - e=0; e<length; e+=2. The < (strict less-than) is your safety guard against going out of bounds.
Topics
Community Discussion
No community discussion yet for this question.