Monday , 15 October 2018
Latest Posts
Home » Array Related Programs » Java Program to check for Upper Triangular Matrix

Java Program to check for Upper Triangular Matrix

Question:

Write a Program in Java to input a 2-D square matrix and check whether it is an Upper Triangular Matrix or not.

Upper Triangular Matrix : An Upper Triangular matrix is a square matrix in which all the entries below the main diagonal (↘) are zero. The entries above or on the main diagonal themselves may or may not be zero.

Example:

$\begin{bmatrix} 5 & 3 & 0 & 7 \\ 0 & 1 & 9 & 8 \\ 0 & 0 & 4 & 6 \\ 0 & 0 & 0 & 2 \end{bmatrix}$

Solution:

/**
* The class UpperTriangularMatrix inputs a Matrix and checks whether it is an Upper Triangular Matrix or not
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.util.*;
class UpperTriangularMatrix
{
public static void main(String args[])throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the matrix : ");
int m=sc.nextInt();
int A[][]=new int[m][m];

/* Inputting the matrix */
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
}
}

/* Printing the matrix */
System.out.println("*************************");
System.out.println("The Matrix is : ");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
System.out.println("*************************");

int p=0;

for(int i=0;i<m;i++)
{
for(int j=0;j<i;j++)
{
/* Checking that the matrix is Upper Triangular or not */
if(A[i][j]!=0) // All elements below the diagonal must be zero
{
p=1;
break;
}
}
}

if(p==0)
System.out.println("The matrix is Upper Triangular");
else
System.out.println("The matrix is not Upper Triangular");
}
}

Output:

Enter the size of the matrix : 4
Enter an element : 5
Enter an element : 3
Enter an element : 0
Enter an element : 7
Enter an element : 0
Enter an element : 1
Enter an element : 9
Enter an element : 8
Enter an element : 0
Enter an element : 0
Enter an element : 4
Enter an element : 6
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 2
*************************
The Matrix is :
5 3 0 7
0 1 9 8
0 0 4 6
0 0 0 2
*************************
The matrix is Upper Triangular

ISC 2017 Computer Science Solution + Examiner’s Comments – From the Council

Solution of ISC 2017 Computer science Paper as provided by the Council for the Indian School Certificate Examinations.

One comment

1. This site teaches better than my 30 year experienced computer teacher