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
I found a simple algorithm to accomplish this task.
Store the square matrix in a single one dimensional array.
Let 'n' be the order of square matrix.
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.
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.
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)'.
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