![]() |
VOOZH | about |
Given an integer matrix mat[][] of odd dimensions, the task is to find the square of the elements of the Primary and Secondary diagonals.
The Primary and Secondary diagonal matrix explanation is given below:
Examples:
Input:
mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]Output: 1 25 81
9 25 49Explanation: Principal Diagonal: {1, 5, 9}, on squaring each element we will get {1, 25, 81}. Secondary Diagonal: {3, 5, 7}, on squaring each element we will get {9, 25, 49}
Input:
mat[][] = [[8]]Output: 64
64Explanation: Principal Diagonal: {8}, on squaring each element we will get {64}. Secondary Diagonal: {8}, on squaring each element we will get {64}
Table of Content
The idea is to traverse the matrix in row-column fashion using the nested loops. The outer loop i is used to traverse all the rows and inner loop j is used traverse all the columns of each row. For each index in the matrix, if i == j, it corresponds to the principal diagonal and if i == n-j-1, it corresponds to the secondary diagonal, where n is the count of columns in each row of the matrix. Traverse the matrix twice, firstly for principal diagonal and then for secondary diagonal. For each element of any of the diagonal, print the square of its value.
1 25 81 9 25 49
Each row in a matrix has only one diagonal element. Instead of checking every column, we can directly calculate the diagonal indices. For the primary diagonal, row and column indices are equal, so we print the square of mat[i][i]. For the secondary diagonal, the column index is n - i - 1, where n is the number of columns, so we can print square of mat[i][n-i-1].
1 25 81 9 25 49