nerdexam
Oracle

1Z0-808 · Question #22

Given the code fragment: int[] array = {1, 2, 3, 4, 5}; And given the requirements: 1. Process all the elements of the array in the order of entry. 2. Process all the elements of the array in the…

The correct answer is B. Requirements 1, 2, and 3 can be implemented by using the standard for loop. D. Requirement 1 can be implemented by using the enhanced for loop. B is correct because the standard for loop gives full control over the index variable - you can iterate forward (i++), backward (i = array.length - 1; i >= 0; i--), or skip elements (i += 2) - making all three requirements achievable. D is correct because the enhanced for loop…

Using Loop Constructs

Question

Given the code fragment: int[] array = {1, 2, 3, 4, 5}; And given the requirements:
  1. Process all the elements of the array in the order of entry.
  2. Process all the elements of the array in the reverse order of entry.
  3. Process alternating elements of the array in the order of entry.
Which two statements are true?

Options

  • ARequirements 1, 2, and 3 can be implemented by using the enhanced for loop.
  • BRequirements 1, 2, and 3 can be implemented by using the standard for loop.
  • CRequirements 2 and 3 CANNOT be implemented by using the standard for loop.
  • DRequirement 1 can be implemented by using the enhanced for loop.
  • ERequirement 3 CANNOT be implemented by using either the enhanced for loop or the standard for loop.

How the community answered

(25 responses)
  • A
    24% (6)
  • B
    60% (15)
  • C
    4% (1)
  • E
    12% (3)

Explanation

B is correct because the standard for loop gives full control over the index variable - you can iterate forward (i++), backward (i = array.length - 1; i >= 0; i--), or skip elements (i += 2) - making all three requirements achievable. D is correct because the enhanced for loop (for (int x : array)) only iterates every element sequentially in insertion order, which satisfies requirement 1 but nothing else.

A is wrong because the enhanced for loop cannot reverse or skip elements - it has no index variable to manipulate. C is wrong because it claims requirements 2 and 3 cannot be done with the standard for loop, which is the opposite of the truth. E is wrong because requirement 3 (alternating elements) is trivially solved with i += 2 in a standard for loop.

Memory tip: Think of the enhanced for loop as "read-only autopilot" - great for simple forward traversal, but the moment you need custom step size or direction, you need the standard for loop's manual index control.

Topics

#enhanced for loop#standard for loop#array iteration#loop control

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice