# Find Sum of Diagonals of Matrix

In this section, you will learn how to find the sum of both diagonals of matrix.

In this section, you will learn how to find the sum of both diagonals of matrix.

### Find Sum of Diagonals of Matrix

You all know that a matrix is a rectangular array of numbers and these numbers in the matrix are called its entries or its elements. Here we are going to find the sum of Primary diagonal (From left top to right bottom)  and Secondary diagonal (From right top to  left bottom) of the matrix from the given two dimensional array.

See the following matrix:

a11 a12 a13
a21 a22 a23
a31 a32 a33

Here a11, a22  and a33 are the elements of primary diagonal and a13, a22 and a31 are the elements of secondary diagonal.

Here is the code:

```import java.io.*;

public class Sum_Diagonal {
public static void main(String args[]) throws IOException {
int d[][] = { { 1, 2, 6 }, { 3, 8, 5 }, { 5, 6, 7 } };
int k = 0, j = 0;
int sum1 = 0, sum2 = 0;
for (j = 0; j < d.length; j++) {
for (k = 0; k < d.length; k++)
System.out.print(d[j][k] + " ");
System.out.println();
}
for (j = 0; j < d.length; j++) {
sum1 = sum1 + d[j][j];
}
k = d.length - 1;
for (j = 0; j < d.length; j++) {
if (k >= 0) {
sum2 = sum2 + d[j][k];
k--;
}
}
System.out.println("Sum of Digonal elements are  :" + sum1 + " and "
+ sum2);
}
}
```

Output:

 1  2  6 3  8  5 5  6  7 Sum of diagonal elements are: 16 and 19