Programming Basics (Pseudocode Tracing)
The following program copies the elements of the 2D array m with 4 rows and 5 columns into the 20-element array b. m[i, j] is the element in row i, column j, and indices start at 1. At which index of b is m[3, 2] stored?
integer: k ← 0
for (i from 1 to 4 step 1)
for (j from 1 to 5 step 1)
k ← k + 1
b[k] ← m[i, j]
endfor
endfor
- A7
- B11
- C12
Show answer and explanation
Answer: C. 12
The outer i is the row and the inner j is the column, so b is filled with the 5 elements of row 1, then the 5 of row 2, then row 3 (row-major order). Before m[3, 2] come the 10 elements of rows 1 and 2 and m[3, 1], so k = 10 + 2 = 12. In general the index is (i − 1) × 5 + j. Using the formula for 0-based indices, (i − 1) × 5 + (j − 1), unchanged gives 11, which is off by one.
- A. This is (j − 1) × 4 + i, for copying column by column (column-major order).
- B. This uses the formula for 0-based indices and is off by one.
- C. Correct. (3 − 1) × 5 + 2 = 12.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions