Java教程

Java显示上三角矩阵

在此程序中,我们需要显示上三角矩阵。

上三角矩阵

上三角矩阵是一个正方形矩阵,其中主对角线以下的所有元素均为零。为了找到上三角矩阵,矩阵必须是正方形矩阵,也就是说,矩阵中的行数和列数必须相等。典型的方阵的尺寸可以用nx n表示。
Java程序显示上三角矩阵
考虑以上示例,给定矩阵的主要对角元素为(1、6、6)。对角线以下的所有元素都必须为零才能将其转换为上三角矩阵,在我们的示例中,这些元素位于位置(2,1),(3,1)和(3,2)。要将给定的矩阵转换为上三角矩阵,请遍历该矩阵并将行号大于列号的元素的值设置为零。

算法

步骤1: START 步骤2: 定义rows,cols 步骤3: 初始化矩阵a[][] = {{1,2,3},{8,6,4},{4,5,6}} 步骤4: rows= a.length 步骤5: cols = a [0].length 步骤6: if(rows!= cols)
然后
PRINT"矩阵应为方矩阵"
else
转到步骤7
步骤7: 直到i < rows
为止,将步骤8重复到步骤10 //for(i = 0; i < rows; i++)
步骤8: 重复步骤9,直到j < cols //for(j=0; j < cols; j++) 步骤9: 如果(i > j)则打印0,否则打印a[i] [j] 步骤10: 打印新行 STEP 11: END

程序

public class UpperTriangular
{
    public static void main(String[] args) {
        int rows, cols;
        //Initialize matrix a
        int a[][] = {
            {1, 2, 3},
            {8, 6, 4},
            {4, 5, 6}
        };
        //Calculates number of rows and columns present in given matrix
          rows = a.length;
        cols = a[0].length;
        if(rows != cols){
            System.out.println("Matrix should be a square matrix");
        }
        else {
            //Performs required operation to convert given matrix into upper triangular matrix
            System.out.println("Upper triangular matrix: ");
            for(int i = 0;i <rows;i++){
                for(int j = 0;j <cols;j++){
                    if(i >j)
                    System.out.print("0 ");
                    else
                    System.out.print(a[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
}
输出:
Upper triangular matrix:
1 2 3
0 6 4
0 0 0
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4