For a given 2D square matrix, the task is to find the sum of elements in the Principle and Secondary diagonals. For example, analyze the following 4 × 4 input matrix.
a00 a01 a02 a03 a10 a11 a12 a13 a20 a21 a22 a23 a30 a31 a32 a33
1. The principal diagonal is constituted by the elements a00, a11, a22, a33, and the row-column condition for the principal diagonal is
row = column
2. However, the secondary diagonal is constituted by the elements a03, a12, a21, a30, and the row-column condition for the Secondary diagonal is
row = number_of_rows – column -1
Input 1 : 6 7 3 4 8 9 2 1 1 2 9 6 6 5 7 2 Output 1 : Principal Diagonal: 26 Secondary Diagonal: 14 Input 2 : 2 2 2 1 1 1 3 3 3 Output 2 : Principal Diagonal: 6 Secondary Diagonal: 6
Sum of Principal Diagonal:35 Sum of Secondary Diagonal:58
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.