Sum of Diagonal Elements of Matrix in Java

Sum of Diagonal Elements of a Matrix in Java | In a matrix the elements located at the position aij where i=j are called diagonal elements. For example, In the matrix “a” the elements located at positions a00, a11, a22 are diagonal elements.

For example:-
Matrix =
1 2 3
4 5 6
7 8 9

Then the diagonal elements are:- 1, 5, 9
Sum of diagonal elements = 1+5+9 = 15

Before solving this problem, you should have knowledge of how to declare and initialize a matrix in Java, how to take input for a matrix from the end-user, and what are the different ways to display it. How to find the length or size of a matrix in Java? How to pass and return a matrix in Java. See:- Matrix in Java

matrix

Procedure to develop a method to find the sum of diagonal elements of a Matrix,
a) Take a matrix.
b) Declare a sum variable and initialize it with 0.
c) Traverse through the matrix.
d) When row and column are equal then add it to the sum.
e) Display the sum value.

In this program, we will directly initialize the matrix with explicit value, but you can take it from the end-user. This program can’t be developed using a for-each loop, because the for-each loop doesn’t contain an index. Therefore we will use for loop to perform the operation.

Java Program to Find the Sum of Diagonal Elements of a Matrix

public class Matrix {

  // main method
  public static void main(String[] args) {

    // declare and initialize a matrix
    int a[][] =  { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    // find sum of diagonal elements
    int sum = diagonalSum(a);
    
    // display result
    System.out.println("Sum of diagonal elements = " + sum);
  }

  // method to find sum of diagonal elements of matrix
  public static int diagonalSum(int[][] a) {
    int sum = 0;
    for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < a[i].length; j++) {
        if(i == j) sum += a[i][j];
      }
    }
    return sum;
  }
}

Output:-

Sum of diagonal elements = 15

See more matrix programs in Java:- 

  1. Program to Print 3×3 Matrix 
  2. Sum of matrix elements in Java
  3. Row sum and Column sum of Matrix in Java
  4. Matrix Addition in Java
  5. Subtraction of two matrices in Java 
  6. Transpose of a Matrix in Java 
  7. Matrix Multiplication in Java
  8. Menu-driven program for Matrix operations

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *