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:
- Initialize a square matrix with values.
- Iterate through the matrix to calculate the sums of both diagonals.
- 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:
- We start by initializing a square matrix
matrix
with sample values. This matrix is a 3×3 matrix in this example. - We declare two variables,
primaryDiagonalSum
andsecondaryDiagonalSum
, to store the sums of the primary and secondary diagonals, respectively. These variables are initialized to 0. - We use a
for
loop to iterate through the matrix. The loop runs from0
ton-1
, wheren
is the number of rows in the matrix (assuming it’s a square matrix). - 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. - 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. - Finally, we print the Matrix and the sums of both diagonals.
See also: Find the Transpose of a Matrix | Search Matrix | Symmetric Matrix Program