Java程序显示矩阵下三角

编写一个Java程序,通过示例显示矩阵的下三角。下三角是其对角线上方的元素为零的方阵。

在此示例中,我们声明了一个整数矩阵。接下来,我们使用for循环来迭代二维数组。在for循环中,我们使用If语句来检查行索引位置是否大于或等于列索引位置。如果为true,则编译器会打印矩阵的原始值。否则,它将打印0值。

public class MatrixLowerTriangle {
	
	public static void main(String[] args) {
		
		int i, j;
		
		int[][] Lt_arr = {{11, 21, 31}, {41, 51, 61}, {71, 81, 91}};
		
		System.out.println("\n---The Lower Triangle of the given Matrix---");
		for(i = 0; i < 3 ; i++)
		{
			System.out.print("\n");
			for(j = 0; j < 3; j++)
			{
				if(i >= j) {
					System.out.format("%d \t", Lt_arr[i][j]);
				}
				else {
					System.out.print("0 \t");	
				}
			}
		}
	}
}
Java Program to display Matrix Lower Triangle

使用for循环显示矩阵下三角的Java程序

此矩阵下三角代码与上述代码相同。但是,此Java代码允许用户输入行数、列数和元素。

import java.util.Scanner;

public class Example {
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		int i, j, rows, columns;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Please Enter LT Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the LT Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr[i][j] = sc.nextInt();
			}		
		}
		System.out.println("\n---The Lower Triangle of the given ---");
		for(i = 0; i < rows ; i++)
		{
			System.out.print("\n");
			for(j = 0; j < columns; j++)
			{
				if(i >= j) {
					System.out.format("%d \t", arr[i][j]);
				}
				else {
					System.out.print("0 \t");	
				}
			}
		}
	}
}
 Please Enter LT Rows and Columns :  
3 3

 Please Enter the LT Items :  
10 20 99
33 55 88
77 89 44

---The Lower Triangle of the given ---

10 	0 	0 	
33 	55 	0 	
77 	89 	44