Header Ads Widget

Develop Your Creative Skill with
Free Design Tutorials

Our blog helps to Provide Latest Tips and Tricks tutorials about Blogging
Business, SEO Tips, much more. this Blog and stay tuned to this
blog for further updates.

sum of diagonal element of a matrix

 Calculate the sum of diagonal elements of a matrix

we are given a square matrix of order NxN and we have to find the sum of diagonal elements of the given matrix.
so we have to sum all elements of the left diagonal and the sum of all elements of the right diagonal of a matrix.


Input: Matrix = [[7,1,5],[1,2,3],[4,0,6]]
Output: 20
Here in this example, we are given a 2D array we get a sum of diagonals as output.

Sum of Left Diagonal elements = 9

sum of right diagonal elements = 11

The total sum of diagonal element = 20

sum of diagonal element of a matrix


Let us understand the logic before going to a solution.
we know that all the elements of the left diagonal are like 
(i=j).
and condition for the right diagonal element is  ( i+j=N-1).
where i and j are position coordinates and N is the size of Matrix.


Sum of diagonal of the matrix in C++

    Here is the implementation of the sum of diagonal elements of the matrix in c++.


int main()
{
int Matrix[3][3]; //get element form user
int N= sizeof(Matrix);
for(int i=0; i<N ; i++){
    for(int j=0; j<N; j++){
      cin >> matrix[i][j];
      if(i==j)
        sumL =sumL + matrix[i][j];
      if((i+j) == N-1)
        sumR = sumR + matrix[i][j];
    }
  }
  cout<<sumR +sumL;
  return 0;
  }


Sum of diagonal of the matrix in Java

Here is the implementation of the sum of diagonal elements of the matrix in the Java programming language.

class Solution {
    public int SumDiagonal(int[][] Matrix) {
        int N=Matrix.length;
        for(int i=0; i<N ; i++){
    for(int j=0; j<N; j++){
      cin >> matrix[i][j];
      if(i==j)
        sumL =sumL + matrix[i][j];
      if((i+j) == N-1)
        sumR = sumR + matrix[i][j];
    }
  }
  
return sumR+sumL;
        
    }
}


Sum of diagonal of the matrix in Python

here is the implementation of the sum of diagonal elements of a 2D array in Python.

Matrix=[[0]*M]*M
sum=0
for i in range(M):
    for j in range(M):
        if i==j:
            sum=sum+Matrix[i][j]
        elif i+j=M-1:
            sum=sum+Matrix[i][j]
print(sum)



in all the implementation we assumed that you already have all elements of the 2D array.

Time Complexity = O(N^2).
Space complexity = O(1).

we made two loops for iterating through all elements of the Matrix to get the sum of diagonal elements of the matrix.

Related Posts :