Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 30: Write a Java program to print the upper triangular matrix of the entered matrix.

UpperTriangle.java

import java.util.Scanner;

public class UpperTriangle
{
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		
		//Input size of the matrix
		//row - number of rows in the matrix.
		//col - number of columns in the matrix.
		
		System.out.println("Enter the number of rows");
		int row = s.nextInt();

		System.out.println("Enter the number of columns");
		int col = s.nextInt();
		
		//Input matrix
		int matrix[][] = new int[row][col];

		System.out.println("Enter the matrix");
		for(int i=0;i < row;i++)
		{
			for(int j=0;j < col;j++)
			{
				System.out.print("Enter "+i+j+" element: ");
				matrix[i][j] = s.nextInt();
			}
		}
		
		System.out.println("upper triangular matrix");
		for(int i=0;i < row;i++)
		{
			for(int j=0;j < col;j++)
			{
				if(i>j)
				{
					System.out.print(0+" ");
				}
				else
				{
					System.out.print(matrix[i][j]+" ");
				}
			}
			System.out.println();
		}
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.