Question
Program to display the upper triangular matrix
(Upper triangular matrix is a square matrix in which all the elements below the principle diagonal will be zero)
Matrix = [9, 8, 7]
[6, 5, 4]
[3, 2, 1]
UPPER TRIANGULAR MATRIX
[9, 8, 7]
[0, 5, 4]
[0, 0, 1]
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class UpperTriangularMatrix
{
public static void main(String[] args)
{
int row=0, col=0,i=0,j=0;
int a[][];
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE ROW OF MATRIX");
row=sc.nextInt();
System.out.println("ENTER THE COLUMN OF MATRIX");
col=sc.nextInt();
if(row!=col)
{
System.out.println("MATRIX NEED TO BE SQUARE MATRIX FIRST!!!");
}
else
{
a=new int[row][col];
System.out.println("ENTER THE ELEMENTS IN MATRIX");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
a[i][j]=sc.nextInt();
}
}
/*if i > j then print 0 else print number present in array at that position */
System.out.println("UPPER TRIANGULAR MATRIX");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
if(i > j)
{
System.out.print("0 ");
}
else
{
System.out.print(a[i][j]+" ");
}
}
System.out.println();
}
}
}
}