Java 程序查找矩阵上三角的和

编写一个 Java 程序来查找矩阵上三角的和,并附带示例。我们已经在之前的示例中解释了显示矩阵上三角的步骤。 

在此 Java 矩阵上三角和示例中,我们声明了一个整数矩阵。接下来,我们使用for 循环来迭代矩阵。在 for 循环内,我们计算给定矩阵上三角的和。

public class SumOfUpperTriangle {
	
	public static void main(String[] args) {
		
		int i, j, sum = 0;
		
		int[][] Ut_arr = {{15, 25, 35}, {45, 55, 65}, {75, 85, 95}};
		
		for(i = 0; i < 3 ; i++)
		{
			for(j = 0; j < 3; j++)
			{
				if(j > i) {
					sum = sum + Ut_arr[i][j];
				}
			}
		}
		System.out.println("\n The Sum of Upper Triangle Matrix =  " + sum);
	}
}
Java Program to find the Sum of the Matrix Upper Triangle

Java 程序查找矩阵上三角的和示例 2

Java上三角矩阵和代码与上述相同。但是,此Java代码允许我们输入行数、列数和矩阵项。

import java.util.Scanner;

public class SumOfUpperTriangle {
	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 Please Enter UT Matrix Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the UT Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr[i][j] = sc.nextInt();
			}		
		}
		
		for(i = 0; i < rows ; i++)
		{
			for(j = 0; j < columns; j++)
			{
				if(j > i) {
					sum = sum + arr[i][j];
				}
			}
		}
		System.out.println("\n The Sum of Upper Triangle Matrix =  " + sum);
	}
}

Java 矩阵上三角和的输出

 Please Enter UT Matrix Rows and Columns :  
3 3

 Please Enter the UT Matrix Items :  
10 20 40
80 90 70
11 14 120

 The Sum of Upper Triangle Matrix =  130