# The sum of Diagonals of a Matrix in Java

In this post, you will learn how to write a program to calculate the Sum of Diagonals of a Matrix in Java. To calculate the sum of both diagonals of a square matrix in Java, you can follow these steps:

1. Initialize a square matrix with values.
2. Iterate through the matrix to calculate the sums of both diagonals.
3. Print the Matrix and the sums of the diagonals.

Here’s the Java program to achieve this with an explanation:

```package com.javacodepoint.array.multidimensional;

public class DiagonalSumOfMatrix {

public static void main(String[] args) {
// Initialize a square matrix (3x3 in this example)
int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

// Calculate the sums of both diagonals
int primaryDiagonalSum = 0;
int secondaryDiagonalSum = 0;

// The number of rows (assuming it's a square matrix)
int n = matrix.length;

for (int i = 0; i < n; i++) {
// Sum of the primary diagonal (top-left to bottom-right)
primaryDiagonalSum += matrix[i][i];

// Sum of the secondary diagonal (top-right to bottom-left)
secondaryDiagonalSum += matrix[i][n - 1 - i];
}

// Print the Matrix
System.out.println("Matrix:");
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}

// Print the sums of both diagonals
System.out.println("Sum of the Primary Diagonal: " + primaryDiagonalSum);
System.out.println("Sum of the Secondary Diagonal: " + secondaryDiagonalSum);
}
}

```

OUTPUT:

Matrix:
1 2 3
4 5 6
7 8 9
Sum of the Primary Diagonal: 15
Sum of the Secondary Diagonal: 15

Explanation:

1. We start by initializing a square matrix `matrix` with sample values. This matrix is a 3×3 matrix in this example.
2. We declare two variables, `primaryDiagonalSum` and `secondaryDiagonalSum`, to store the sums of the primary and secondary diagonals, respectively. These variables are initialized to 0.
3. We use a `for` loop to iterate through the matrix. The loop runs from `0` to `n-1`, where `n` is the number of rows in the matrix (assuming it’s a square matrix).
4. Inside the loop, we update `primaryDiagonalSum` by adding the value of the element at position `[i][i]`, which corresponds to the elements on the primary diagonal from top-left to bottom-right.
5. We update `secondaryDiagonalSum` by adding the value of the element at position `[i][n - 1 - i]`, which corresponds to the elements on the secondary diagonal from top-right to bottom-left.
6. Finally, we print the Matrix and the sums of both diagonals.