ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode? (A square matrix's main diagonal is mat[i][i]; its anti-diagonal is mat[i][n-1-i]. If n is odd, the centre cell belongs to both and must not be counted twice.)

What will be the output of the following pseudocode? (A square matrix's main diagonal is mat[i][i]; its anti-diagonal is mat[i][n-1-i]. If n is odd, the centre cell belongs to both and must not be counted twice.)
Integer n = 5
Integer mat[5][5] = {{10, 10, 10, 13, 11}, {18, 8, 14, 5, 19}, {10, 14, 17, 4, 11}, {7, 10, 15, 1, 16}, {15, 1, 11, 18, 8}}
Integer total = 0
for (each i from 0 to n - 1)
    total = total + mat[i][i]
    if (i != n - 1 - i)
        total = total + mat[i][n - 1 - i]
    end if
end for
Print total
  1. A. 86
  2. B. 85
  3. C. 84
  4. D. 102

Correct answer: B. 85

Summing both diagonals of this 5×5 matrix: main diagonal = 44, anti-diagonal = 58, minus the centre cell (17) counted twice, giving 85. Simply adding both sums without removing the double-counted centre gives the trap 102.

More Pseudocode and Code Tracing questions

Exams that ask this topic