Java程序查找矩阵对角线元素之和

编写一个Java程序,通过示例查找矩阵对角线元素之和。或者Java程序计算矩阵或多维数组中对角线元素的和。在此Java矩阵对角线元素之和示例中,我们声明了一个带有随机值的3x3 SumOppdia_arr整数矩阵。接下来,我们使用for循环迭代SumOppdia_arr矩阵项。在for循环中,我们正在查找SumOppdia_arr矩阵中对角线元素的和。

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);

	}
}

Java矩阵对角线元素之和的输出

The Sum of Matrix Opposite Diagonal Items = 150

Java程序查找矩阵对角线元素之和示例2

这个Java矩阵对角线元素之和代码与上面的相同。在这里,我们添加了一个额外的语句来显示对角线位置的值。

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);

	}
}
Java Program to find Sum of Matrix Opposite Diagonal

这个Java矩阵对角线元素之和代码与上面的相同。但是,这个用于矩阵对角线元素之和的Java代码允许用户输入行、列和矩阵项。

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