Programming Basics (Pseudocode Tracing)

m[i, j] is the element in row i, column j of the 2D array m, and indices start at 1. What is the value of s after the following program runs?

2D integer array: m ← {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
integer: s ← 0
for (i from 1 to 3 step 1)
  for (j from 1 to i step 1)
    s ← s + m[i, j]
  endfor
endfor
  1. A15
  2. B26
  3. C34
Show answer and explanation

Answer: C. 34

Each inner {…} is one row. j runs from 1 to i, so row 1 adds m[1, 1] = 1, row 2 adds 4 + 5 and row 3 adds 7 + 8 + 9, giving s = 1 + 9 + 24 = 34. This is the sum of the diagonal and the elements below it (the lower triangle). Mixing up rows and columns as m[j, i] would add the upper triangle instead: 1 + 2 + 5 + 3 + 6 + 9 = 26.

  • A. This adds only the diagonal, 1 + 5 + 9. j runs from 1 to i.
  • B. This mixes up rows and columns and adds the upper triangle.
  • C. Correct. The lower triangle: 1 + 4 + 5 + 7 + 8 + 9 = 34.
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. 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?
  2. Array indices start at 1, and + concatenates strings. What is the value of r after the following program runs?
  3. 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?
  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 f return when called as f(9087)?
  5. ÷ 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)?