Java Program to Check Whether a Given Matrix Is Lower Triangular Matrix or Not

You are currently viewing Java Program to Check Whether a Given Matrix Is Lower Triangular Matrix or Not

Java program to check whether a given matrix is Lower Triangular Matrix or not

import java.util.Scanner;

public class ExArrayLowerMatrix {
  public static void main(String args[]) throws Exception {
    // create object of scanner class
    Scanner sc = new Scanner(System.in);

    // enter the size.
    System.out.print("Enter the size of the matrix : ");

    int m = sc.nextInt();
    int A[][] = new int[m][m];

    // Input the matrix.
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < m; j++) {
        System.out.print("Enter the elements : ");
        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 = i + 1; j < m; j++) {
        // check for lower matrix or not.
        if (A[i][j] != 0) {
          p = 1;
          break;
        }
      }
    }

    // print matrix is lower triangular or not.
    if (p == 0)
      System.out.println("The matrix is Lower Triangular");
    else
      System.out.println("The matrix is not Lower Triangular");
  }
}

Output

First run:
Enter the size of the matrix : 5
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Enter an element : 1
Enter an element : 0
Enter an element : 12
Enter an element : 5
Enter an element : 9
Enter an element : 3
Enter an element : 6
Enter an element : 5
Enter an element : 8
Enter an element : 2
Enter an element : 5
Enter an element : 8
Enter an element : 2
Enter an element : 5
Enter an element : 2
Enter an element : 5
*************************
The Matrix is : 
1	2	3	4	5	
6	7	8	9	1	
0	12	5	9	3	
6	5	8	2	5	
8	2	5	2	5	
*************************
The matrix is not Lower Triangular

Second run:
Enter the size of the matrix : 3
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 1
Enter an element : 0
Enter an element : 0
Enter an element : 1
Enter an element : 1
Enter an element : 0
*************************
The Matrix is : 
0	0	0	
1	0	0	
1	1	0	
*************************
The matrix is Lower Triangular

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply