Java Program to display Matrix Upper Triangle

Write a Java Program to display Matrix Upper Triangle with an example. A Java Matrix Upper triangle is a square matrix whose below the diagonal items are zeros.

In this Java Matrix Upper Triangle example, we declared an integer matrix. Next, we used for loop to iterate the Matrix. Within the for loop, we used the If statement to check whether the columns index position is greater than or equals to the row index position. If it is true, the compiler prints the original value; otherwise, it returns 0’s.

public class MatrixUpperTriangle {
	
	public static void main(String[] args) {
		
		int i, j;
		
		int[][] Ut_arr = {{14, 21, 31}, {44, 51, 64}, {74, 81, 94}};
		
		System.out.println("\n---The Upper Triangle of the given Matrix---");
		for(i = 0; i < 3 ; i++)
		{
			System.out.print("\n");
			for(j = 0; j < 3; j++)
			{
				if(j >= i) {
					System.out.format("%d \t", Ut_arr[i][j]);
				}
				else {
					System.out.print("0 \t");	
				}
			}
		}
	}
}
Java Program to display Matrix Upper Triangle 1

Java Program to display Matrix Upper Triangle example 2

This Java Matrix Upper Triangle code is the same as the above. However, this Java code allows the user to enter the number of rows, columns, and the Matrix items.

import java.util.Scanner;

public class MatrixUpperTriangle {
	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 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();
			}		
		}
		System.out.println("\n---The Upper Triangle of the given Matrix---");
		for(i = 0; i < rows ; i++)
		{
			System.out.print("\n");
			for(j = 0; j < columns; j++)
			{
				if(j >= i) {
					System.out.format("%d \t", arr[i][j]);
				}
				else {
					System.out.print("0 \t");	
				}
			}
		}
	}
}

Java Matrix Upper Triangle output

 Please Enter UT Matrix Rows and Columns :  
3 3

 Please Enter the UT Matrix Items :  
10 20 30
40 50 60
70 80 90

---The Upper Triangle of the given Matrix---

10 	20 	30 	
0 	50 	60 	
0 	0 	90