Which diagonal is being added — Pseudocode Aptitude Question
Which diagonal is being added: The matrix M is 1-indexed in both dimensions. What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 105 seconds
Question
The matrix M is 1-indexed in both dimensions. What is printed?
Integer M[1..3][1..3], i, j, s
Set M = { {2, 7, 1},
{9, 4, 6},
{3, 8, 5} }
Set s = 0
For i = 1 to 3
For j = 1 to 3
If i + j == 4 Then
Set s = s + M[i][j]
End If
End For
End For
Print sOptions
- 8
- 11
- 19
- 45
Show the answer and the worked solution
Correct answer: A. 8
Worked solution
- The pairs with i + j = 4 are (1, 3), (2, 2) and (3, 1).
- Those cells hold M[1][3] = 1, M[2][2] = 4 and M[3][1] = 3.
- The sum is 1 + 4 + 3 = 8.
Answer: 8.
The idea
For an n by n matrix the main diagonal satisfies i = j and the anti-diagonal satisfies i + j = n + 1. Here the main diagonal would total 11, which is the distractor.
Shortcut. i + j = 4 is the line from the top-right corner through the centre to the bottom-left corner: 1 + 4 + 3 = 8.
Common trap. 11 is 2 + 4 + 5, the main diagonal, which is what adding the cells where i = j gives instead of those where i + j = 4.