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
  1. A7
  2. B11
  3. 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.
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. Array indices start at 1, and + concatenates strings. What is the value of r after the following program runs?
  2. The following function isPal returns true if the characters in the string array s read the same forward and backward (a palindrome). Array indices start at 1. What should replace 【a】 in the program?
  3. ÷ is division; when the result is assigned to an integer variable (including a function argument), the fractional part is discarded. What does the following function f return when called as f(9087)?
  4. ÷ is division; when the result is assigned to an integer variable (including a function argument), the fractional part is discarded. What does the following function toBin return when called as toBin(12)?
  5. The following program subtracts the two integers a and b from each other until they are equal. What is the value of k after it runs?