1Z0-811 · Question #49
Given the code fragment: int[] arr = {1, 2, 3, 4, 5}; Which for loop statement can be used to print 135?
The correct answer is D. for(int idx = 0; idx < arr.length; idx+=2) { System.out.print(arr[idx]); }. Option D works because starting at index 0 and stepping by 2 visits indices 0, 2, 4, which hold values 1, 3, 5 - exactly the target output. The key insight is that the odd-valued elements (1, 3, 5) happen to sit at even indices (0, 2, 4). Option A is a close trap: it also steps…
Question
Options
- Afor(int idx = 1; idx < arr.length; idx+=2) { System.out.print(arr[idx]); }
- Bfor(int idx = 1; idx < arr.length-1; idx++) { System.out.print(arr[idx+1]); }
- Cfor(int idx = 0; idx < arr.length; idx++) { System.out.print(arr[idx]); }
- Dfor(int idx = 0; idx < arr.length; idx+=2) { System.out.print(arr[idx]); }
How the community answered
(20 responses)- A5% (1)
- B5% (1)
- C10% (2)
- D80% (16)
Explanation
Option D works because starting at index 0 and stepping by 2 visits indices 0, 2, 4, which hold values 1, 3, 5 - exactly the target output. The key insight is that the odd-valued elements (1, 3, 5) happen to sit at even indices (0, 2, 4).
Option A is a close trap: it also steps by 2, but starts at index 1, hitting indices 1 and 3 (values 2 and 4) - printing 24 instead.
Option C steps by 1 through every index, printing the entire array 12345.
Option B shifts the access by 1 (arr[idx+1]) and restricts the range, ultimately printing 345.
Memory tip: When you need to print every other element starting from the first, remember "zero and skip two" - idx = 0, idx+=2. If a loop starts at index 1 with idx+=2, it targets the second, fourth, sixth... elements, not the first.
Topics
Community Discussion
No community discussion yet for this question.