Google News
logo
Java Program to display the Upper Triangular Matrix
In the following examples of Java program to display the upper triangular matrix of a given square matrix :
Program :
public class UpperTriangularMatrix {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        printUpperTriangularMatrix(matrix);
    }

    public static void printUpperTriangularMatrix(int[][] matrix) {
        int n = matrix.length;
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output :
1 2 3 
5 6 
9 
In this program, we have a square matrix matrix represented as a two-dimensional array. We define a method printUpperTriangularMatrix that takes the matrix as input and prints its upper triangular matrix to the console.

We first calculate the size of the matrix using its length. We then use two nested loops to iterate over the elements of the matrix. The outer loop iterates over the rows, and the inner loop iterates over the columns from the current row index up to the end of the row.

We then print each element of the upper triangular matrix followed by a space. At the end of each row, we print a newline character to move to the next line.