Write a Java Program to find Sum of Matrix Opposite Diagonal Items with an example. Or Java Program to calculate the sum of the opposite diagonal elements in a Matrix or multi-dimensional array. In this Java sum of Matrix opposite Diagonal Items example, we declared a 3 * 3 SumOppdia_arr integer matrix with random values. Next, we used for loop to iterate the SumOppdia_arr Matrix items. Within the for loop, we are finding the sum of opposite diagonal items in a SumOppdia_arr Matrix.
public class SumOfOppositeDiagonals { public static void main(String[] args) { int i, sum = 0; int[][] SumOppdia_arr = {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}}; int len = SumOppdia_arr.length; for(i = 0; i < len ; i++) { sum = sum + SumOppdia_arr[i][len - i - 1]; } System.out.println("\nThe Sum of Matrix Opposite Diagonal Items = " + sum); } }
Output of a Java Matrix Opposite Diagonal sum
The Sum of Matrix Opposite Diagonal Items = 150
Java Program to find Sum of Matrix Opposite Diagonal Items example 2
This Java Matrix sum of Opposite Diagonal Items code is the same as the above. Here, we added one more statement to display the values at the diagonal position.
public class SumOfOppositeDiagonals { public static void main(String[] args) { int i, sum = 0; int[][] SumOppdia_arr = {{15, 25, 35}, {45, 55, 65}, {75, 85, 95}}; int len = SumOppdia_arr.length; for(i = 0; i < len ; i++) { System.out.format("\nThe Matrix Item at " + i + "," + (len - i - 1) + " position = " + SumOppdia_arr[i][len - i - 1]); sum = sum + SumOppdia_arr[i][len - i - 1]; } System.out.println("\nThe Sum of Matrix Opposite Diagonal Items = " + sum); } }
This Java Matrix sum of Opposite Diagonal Items code is the same as the above. However, this Java code for Matrix sum of opposite diagonal allow the user to enter the rows, columns, and the matrix items.
import java.util.Scanner; public class SumOfOppositeDiagonals { 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[][] SumOppdia_arr = new int[rows][columns]; System.out.println("\n Please Enter the Matrix Items : "); for(i = 0; i < rows; i++) { for(j = 0; j < columns; j++) { SumOppdia_arr[i][j] = sc.nextInt(); } } for(i = 0; i < rows ; i++) { System.out.format("\nThe Matrix Item at " + i + "," + (rows - i - 1) + " position = " + SumOppdia_arr[i][rows - i - 1]); sum = sum + SumOppdia_arr[i][rows - i - 1]; } System.out.println("\nThe Sum of Matrix Opposite Diagonal Items = " + sum); } }
Enter Matrix Rows and Columns :
3 3
Please Enter the Matrix Items :
5 15 25
6 35 45
200 10 9
The Matrix Item at 0,2 position = 25
The Matrix Item at 1,1 position = 35
The Matrix Item at 2,0 position = 200
The Sum of Matrix Opposite Diagonal Items = 260