Java Program to find Sum of Matrix Diagonal

Write a Java Program to find Sum of Matrix Diagonal Items with an example. Or Java Program to calculate sum of the Matrix or multi-dimensional array diagonal items.

In this Java sum of Matrix Diagonal Items example, we declared a 3 * 3 Sod_arr integer matrix with random values. Next, we used for loop to iterate the Sod_arrMatrix items. Within the for loop, we are calculating the sum of diagonal items in a Sod_arr Matrix.

public class SumOfDiagonals {
	
	public static void main(String[] args) {
		
		int i, sum = 0;	
	
		int[][] Sod_arr = {{15, 25, 35}, {45, 55, 65}, {75, 85, 95}};
	
		for(i = 0; i < Sod_arr.length ; i++)
		{
				sum = sum + Sod_arr[i][i];
		}
	System.out.println("\nThe Sum of the Matrix Diagonal Items = " + sum);

	}
}

Output of a Java matrix diagonal sum

The Sum of the Matrix Diagonal Items = 165

Java Program to find Sum of Matrix Diagonal Items example 2

This Java Matrix sum of Diagonal Items code is the same as the above. However, here, we added one more statement to display the values in the diagonal position.

public class SumOfDiagonals {
	
	public static void main(String[] args) {
		
		int i, sum = 0;	
	
		int[][] Sod_arr = {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}};
	
		for(i = 0; i < Sod_arr.length ; i++)
		{
			System.out.format("\nThe Matrix Item at " + i + "," + i +
					" position = " + Sod_arr[i][i]);
			sum = sum + Sod_arr[i][i];
		}
	System.out.println("\nThe Sum of the Matrix Diagonal Items = " + sum);

	}
}
Java Program to find Sum of Matrix Diagonal 2

This Java code for Matrix sum of Diagonal Items is the same as the above. However, this Java sum of matrix diagonal code allows the user to enter the number of rows, columns, and the matrix items.

import java.util.Scanner;

public class SumOfDiagonals {
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		int i, j, rows, columns, sum = 0;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Enter Matrix Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] Sod_arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the Sparse Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				Sod_arr[i][j] = sc.nextInt();
			}		
		}
	
		for(i = 0; i < Sod_arr.length ; i++)
		{
			System.out.format("\nThe Matrix Item at " + i + "," + i +
					" position = " + Sod_arr[i][i]);
			sum = sum + Sod_arr[i][i];
		}
	System.out.println("\nThe Sum of the Matrix Diagonal Items = " + sum);

	}
}
 Enter Matrix Rows and Columns :  
3 3

 Please Enter the Sparse Matrix Items :  
11 22 33
44 55 66
77 88 99

The Matrix Item at 0,0 position = 11
The Matrix Item at 1,1 position = 55
The Matrix Item at 2,2 position = 99
The Sum of the Matrix Diagonal Items = 165