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] = {{12, 3, 8, 15, 15}, {8, 11, 7, 19, 17}, {14, 6, 18, 16, 16}, {11, 1, 6, 1, 5}, {8, 3, 12, 14, 1}}
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. 85
  2. B. 87
  3. C. 104
  4. D. 86

Correct answer: D. 86

Summing both diagonals of this 5×5 matrix: main diagonal = 43, anti-diagonal = 61, minus the centre cell (18) counted twice, giving 86. Simply adding both sums without removing the double-counted centre gives the trap 104.

More Pseudocode and Code Tracing questions

Exams that ask this topic