Program to find the sum of diagonal elements of a 2D array

Posted on 09th March 2021

To calculate the sum of diagonal elements of a square matrix or a 2-D array, add all elements on the principal diagonal and anti-diagonal. Principal diagonal, also called main diagonal, consists of elements that are on the line joining the top-left and bottom-corner of the matrix. While, anti-diagonal, also called secondary diagonal, contains all elements from the top right corner to the bottom left of the matrix.

Given a 2-D array of size 3x3 shown below, the elements on the principal diagonal are 1, 3, 2 and elements on the secondary diagonal are 8, 3, 6.

Matrix diagonals
Diagonals of a 2-D array

The sum of diagonal elements = 1+3+2+8+3+6 = 20.

Note that if the array size is an odd number you will have an element on the centre which will be on both the main diagonal and secondary diagonal. In the above array, number 3 is the central element.

You can determine if an element is a diagonal element or not based on its position in the array. The row and column positions (zero-based index) of diagonal elements in the above array are:

Main diagonal => (0,0), (1,1), (2,2)
Secondary diagonal => (0,2), (1,1), (2,0)

You may notice that the row and column indices are the same for elements on the main diagonal. For the secondary diagonal, the sum of the row index and column index is equal to the length of the array minus 1. This can be summarised as

Consider a square matrix a of size NxN, say
row index i = 0 to N - 1 
column index j = 0 to N -1

Then, for each element a(i,j) in the array,
if (i == j), then, the element  a(i,j) is in the main diagonal.  
If ((i + j) < N - 1), then  a(i,j) is in the secondary diagonal.

Here is a Java program that uses the above logic to calculate the sum of diagonal elements of an array.

public class Main {

  public static void main(String[] args) {
    int[][] dataset = {{1, 5, 8},
		{4, 3, 1},
		{6, 5, 2}};

    System.out.println("Diagonal sum is " + DiagonalSum(dataset));
  }

  /**
  * Calculate the sum of diagonal elements.
  * @param a : 2-D array.
  * @return sum of diagonal elements.
  */
  private static int DiagonalSum(int[][] a) {
    int sum = 0;
    for (int i = 0; i < a.length; i++)
      for (int j = 0; j < a[0].length; j++) {
         // Check for main diagonal element.
         if (i == j) {
            sum += a[i][j];
         }
        
         // Check for secondary diagonal element.
         if (i + j == a.length - 1) {
            sum += a[i][j];
         }
       }
     return sum;
    }

}

Output:

Diagonal sum is 23

On an odd size matrix, you might want to add the central element only once, in which case the function can be modified as below.

private static int DiagonalSum(int[][] a) {
   int sum = 0;
   for (int i = 0; i < a.length; i++)
      for (int j = 0; j < a[0].length; j++) {
         // Check for main diagonal element.
         if (i == j) {
            sum += a[i][j];
         }
         
         // Check for secondary diagonal element except central element.
         if (i + j == a.length - 1 && i != j) {
            sum += a[i][j];
         }
     }
  return sum;
}

Output:

Diagonal sum is 20

Post a comment

Comments

Nothing yet..be the first to share wisdom.