QuestionQ117

Using Loop Constructs

Given the following code fragment:

Question Image

Which inserted code will print DCBA?

  • A
  • B
  • C
  • D
Explanation

The list holds four elements at indexes 0 through 3. Initializing the index to the list size (4) and looping while it is at least 1, each iteration pre-decrements the index before calling get, so the elements at indexes 3, 2, 1, and 0 are printed in that order, producing DCBA. Starting from size minus 1 but looping only while the index is at least 1 stops before index 0 and prints only DCB; resetting the index to the list size inside the loop reprints the last element forever; and post-decrementing from the list size accesses index 4 first, which throws an IndexOutOfBoundsException.

Community Discussion

No comments yet. Be the first to start the discussion!