ProgrammingVery hardTCS 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] = {{8, 1, 2, 5, 12}, {14, 18, 13, 7, 1}, {19, 4, 11, 16, 1}, {7, 5, 15, 15, 4}, {20, 15, 16, 5, 4}}
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. 101
  2. B. 100
  3. C. 111
  4. D. 99

Correct answer: B. 100

Summing both diagonals of this 5×5 matrix: main diagonal = 56, anti-diagonal = 55, minus the centre cell (11) counted twice, giving 100. Simply adding both sums without removing the double-counted centre gives the trap 111.

More Pseudocode and Code Tracing questions

Exams that ask this topic