Sum of diagonal elements in a matrix

后端 未结 11 2495
有刺的猬
有刺的猬 2021-02-12 11:35

I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happen

11条回答
  •  灰色年华
    2021-02-12 12:25

    I found a simple algorithm to accomplish this task.

    1. Store the square matrix in a single one dimensional array.

    2. Let 'n' be the order of square matrix.

    3. There are two diagonals , one that starts from the leftmost element in top row and another that starts from nth element of the top row.

    4. To get the indexes of numbers on the diagonal that starts from left most element in top row ,from the array containing all the numbers in the matrix; just add (n+1) recursively starting from index 1. That is, indexes of elements in left to right diagonal in the array are, 1, 1+(n+1) , (n+2)+(n+1) , (2n+3)+(n+1) till the last index of array.

    5. To get the indexes of another diagonal's numbers from the array containing all the numbers in the matrix ; just add (n-1) recursively to the indexes starting from index equals to the 'n', which is the order of the square matrix. That is, indexes of elements in right to left diagonal in the array are, n, n+(n-1), (2n-1)+(n-1) and so on till the index equals to 'length of the array - (n-1)'.

    6. If the order is odd then subtract the middle number in the array from the final sum.

    The example 'c++' code is as follows:

     #include
     using namespace std;
    
    int sumOfDiagonalNumbersInSquareMatrix(int numberArray[],int order){
    int sumOfLeftToRightDiagonal = 0;
    int sumOfRightToLeftDiagonal = 0;
    int length = order*order;
    for(int i=0; i

    You can run it here: http://cpp.sh/6cmdp

提交回复
热议问题