The utilization of 2-dimensional arrays or matrices is extremely advantageous for several applications. Matrix rows and columns are used to hold numbers. We can define 2D matrices in C++ using multi-dimensional arrays as well. In this article, we'll look...
The utilization of 2-dimensional arrays or matrices is extremely advantageous for several applications. Matrix rows and columns are used to hold numbers. We can define 2D matrices in C++ using multi-dimensional arrays as well. In this article, we'll look at how to use C++ to calculate the diagonal sum of a given square matrix.
The matrices h**e two diagonals, the main diagonal and the secondary diagonal (sometimes referred to as major and minor diagonals). The major diagonal starts from the top-left corner (index [0, 0]) to the bottom-right corner (index [n-1, n-1]) where n is the order of the square matrix. The major diagonal starts from top-right corner (index [n-1, 0]) to bottom-left corner (index [0, n-1]). Let us see the algorithm to find the sum of the elements along with these two diagonals.
Sum of all elements in major diagonal: (8 + 7 + 9) = 24 Sum of all elements in minor diagonal: (3 + 7 + 2) = 12
In the previous example, one 3 x 3 matrix was used. We h**e scanned the diagonals individually and calculated the sum. Let us see the algorithm and implementation for a clear view.
For the first matrix: The sum of major diagonal: 129 The sum of minor diagonal: 359 For the second matrix: The sum of major diagonal: 74 The sum of minor diagonal: 194
In this article, we h**e seen how to calculate the diagonal sums of a given square matrix. The major diagonal starts from the top-left corner to the bottom-right corner and the minor diagonal starts from the top-right corner to the bottom-left corner. To find the sum of these diagonal elements, we loop through all elements. When both row and column index values are the same, it indicates the major diagonal element, and when the sum of two indices is the same as n – 1 where n is the order of the matrix, it will add to the minor diagonal. This procedure takes two nested loops and we are tr**ersing through all elements present in the 2D array. So it will take O(n2) amount of time to compute the sum of two diagonals of the given matrix.