AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easyarrays0-indexed

~60s

Walking an array backwards

The array A is 0-indexed, so its elements are A[0] to A[4]. What is printed, in order?

Integer A[0..4], i
Set A = {3, 8, 1, 9, 4}
For i = 4 down to 0
    Print A[i]
End For
Show the answer and the worked solution

Correct answer: B.

4 9 1 8 3

Worked solution

  1. A[4] = 4, A[3] = 9, A[2] = 1, A[1] = 8 and A[0] = 3.
  2. The loop visits those indices in exactly that descending order.
  3. The printed sequence is therefore 4 9 1 8 3.

Answer: 4 9 1 8 3.

The idea

With 0-based indexing an array of n elements ends at index n − 1. Reading the elements off in the loop's own order avoids reversing the answer by accident.

Shortcut. A loop from the last index down to 0 prints the array reversed, so read {3, 8, 1, 9, 4} from right to left.

Common trap. "3 8 1 9 4" is the array in stored order, picked by reading "For i = 4 down to 0" as if the counter went up.

Walking an array backwards — Pseudocode Aptitude Question

Walking an array backwards: The array A is 0-indexed, so its elements are A[0] to A[4]. What is printed, in order? Answer and worked solution on CodeKairo.

Question

The array A is 0-indexed, so its elements are A[0] to A[4]. What is printed, in order?

Integer A[0..4], i
Set A = {3, 8, 1, 9, 4}
For i = 4 down to 0
    Print A[i]
End For

Options

  1. 3 8 1 9 4
  2. 4 9 1 8 3
  3. 4 3 8 1 9
  4. 9 4 3 8 1
Show the answer and the worked solution

Correct answer: B. 4 9 1 8 3

Worked solution

  1. A[4] = 4, A[3] = 9, A[2] = 1, A[1] = 8 and A[0] = 3.
  2. The loop visits those indices in exactly that descending order.
  3. The printed sequence is therefore 4 9 1 8 3.

Answer: 4 9 1 8 3.

The idea

With 0-based indexing an array of n elements ends at index n − 1. Reading the elements off in the loop's own order avoids reversing the answer by accident.

Shortcut. A loop from the last index down to 0 prints the array reversed, so read {3, 8, 1, 9, 4} from right to left.

Common trap. "3 8 1 9 4" is the array in stored order, picked by reading "For i = 4 down to 0" as if the counter went up.

All Pseudocode questions · placement mock tests