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
- A15
- B26
- 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.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions