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.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
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 ForOptions
- 3 8 1 9 4
- 4 9 1 8 3
- 4 3 8 1 9
- 9 4 3 8 1
Show the answer and the worked solution
Correct answer: B. 4 9 1 8 3
Worked solution
- A[4] = 4, A[3] = 9, A[2] = 1, A[1] = 8 and A[0] = 3.
- The loop visits those indices in exactly that descending order.
- 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.