ProgrammingHardAccenture · Cognizant 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 = 3
Integer mat[3][3] = {{8, 17, 13}, {13, 16, 11}, {5, 6, 20}}
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. 62
  2. B. 61
  3. C. 63
  4. D. 78

Correct answer: A. 62

Summing both diagonals of this 3×3 matrix: main diagonal = 44, anti-diagonal = 34, minus the centre cell (16) counted twice, giving 62. Simply adding both sums without removing the double-counted centre gives the trap 78.

More Pseudocode and Code Tracing questions

Exams that ask this topic