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 of integer type 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.

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 Diagonal Items = " + sum);

	}
}
The Sum of the 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 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 Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] Sod_arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the 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 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 Rows and Columns :  
3 3

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

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