ProgrammingVery hardAccenture · 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 = 5
Integer mat[5][5] = {{1, 7, 1, 14, 10}, {8, 11, 9, 8, 6}, {8, 17, 10, 17, 18}, {16, 2, 6, 16, 19}, {3, 1, 16, 13, 16}}
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. 77
  2. B. 87
  3. C. 78
  4. D. 76

Correct answer: A. 77

Summing both diagonals of this 5×5 matrix: main diagonal = 54, anti-diagonal = 33, minus the centre cell (10) counted twice, giving 77. Simply adding both sums without removing the double-counted centre gives the trap 87.

More Pseudocode and Code Tracing questions

Exams that ask this topic