KnowledgeBoat Logo

Computer Science

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

Lower Triangular Matrix: A Lower Triangular matrix is a square matrix in which all the entries above the main diagonal [] are zero. The entries below or on the main diagonal must be non zero values.

Enter the size of the matrix: 4
The Matrix is:
5 0 0 0
3 1 0 0
4 9 4 0
6 8 7 2

The Matrix is Lower Triangular

Java

Java Arrays

16 Likes

Answer

import java.util.Scanner;

public class KboatLowerTriangularMatrix
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the size of the matrix: ");
        int n = in.nextInt();
        
        int arr[][] = new int[n][n];
        
        System.out.println("Enter elements of the matrix: ");
        for (int i = 0; i < n; i++) {
            System.out.println("Enter Row "+ (i+1) + " :");
            for (int j = 0; j < n; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        System.out.println("The Matrix is:");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
        
        boolean isTriangular = true;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if ((i < j && arr[i][j] != 0)
                     || (i >= j && arr[i][j] == 0)) {
                    isTriangular = false;
                    break;
                }
            }
            
            if (!isTriangular) {
                break;
            }
        }
        
        if (isTriangular) {
            System.out.println("The Matrix is Lower Triangular");
        }
        else {
            System.out.println("The Matrix is not Lower Triangular");
        }
    }
}

Output

BlueJ output of Write a Program in Java to input elements in a 2D square matrix and check whether it is a Lower Triangular Matrix or not. Lower Triangular Matrix: A Lower Triangular matrix is a square matrix in which all the entries above the main diagonal [] are zero. The entries below or on the main diagonal must be non zero values. Enter the size of the matrix: 4 The Matrix is: 5 0 0 0 3 1 0 0 4 9 4 0 6 8 7 2 The Matrix is Lower Triangular

Answered By

5 Likes


Related Questions