ProgrammingHardWipro · TCS NQT 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] = {{11, 2, 10, 15, 6}, {1, 7, 9, 7, 4}, {3, 15, 8, 15, 19}, {2, 7, 14, 4, 15}, {19, 5, 16, 2, 10}}
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. 79
  2. B. 78
  3. C. 80
  4. D. 87

Correct answer: A. 79

Summing both diagonals of this 5×5 matrix: main diagonal = 40, anti-diagonal = 47, minus the centre cell (8) counted twice, giving 79. 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