Java Program to display the lower triangular matrix

In this program, we need to display the lower triangular matrix.

Lower Triangular Matrix

Lower triangular matrix is a square matrix in which all the elements above the principle diagonal will be zero. To find the lower triangular matrix, a matrix needs to be a square matrix that is, the number of rows and columns in the matrix need to be equal. Dimensions of a typical square matrix can be represented by n x n.

Java Program to display the lower triangular matrix

Consider the above example, principle diagonal element of given matrix is (1, 6, 6). All the elements above the diagonal needs to made zero. In our example, those elements are at positions (1, 2), (1, 3) and (2, 3). To convert given matrix into the lower triangular matrix, loop through the matrix and set the values of the element to zero where column number is greater than row number.

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE rows, cols
  • STEP 3: INITIALIZE matrix a[][] ={{1,2,3},{8, 6, 4}, {4, 5, 6}}
  • STEP 4: rows = a.length
  • STEP 5: cols = a[0].length
  • STEP 6: if(rows!=cols)
            then
            PRINT “Matrix should be a square matrix”
            else
            Go to step 7
  • STEP 7: REPEAT STEP 4 to STEP 6 UNTIL i<rows
            //for(i=0; i<rows; i++)
  • STEP 8: REPEAT STEP 9 UNTIL j<cols // for(j=0; j<cols; j++)
            If(j>i) then PRINT 0 else PRINT a[i][j]
  • STEP 9: PRINT new line
  • STEP 10: END

Program

  1. public class LowerTriangular    
  2. {    
  3.     public static void main(String[] args) {    
  4.     int rows, cols;    
  5.     //Initialize matrix a    
  6.         int a[][] = {       
  7.                         {1, 2, 3},    
  8.                         {8, 6, 4},    
  9.                         {4, 5, 6}    
  10.                     };    
  11.               
  12.           //Calculates number of rows and columns present in given matrix    
  13.           rows = a.length;    
  14.           cols = a[0].length;    
  15.             
  16.           if(rows != cols){    
  17.               System.out.println(“Matrix should be a square matrix”);    
  18.           }    
  19.           else {    
  20.               //Performs required operation to convert given matrix into lower triangular matrix    
  21.               System.out.println(“Lower triangular matrix: “);    
  22.               for(int i = 0; i < rows; i++){    
  23.                   for(int j = 0; j < cols; j++){    
  24.                     if(j > i)    
  25.                       System.out.print(“0 “);    
  26.                     else    
  27.                       System.out.print(a[i][j] + ” “);    
  28.                 }    
  29.                 System.out.println();    
  30.             }    
  31.         }    
  32.     }    
  33. }    

Output:

Lower triangular matrix:
1	0   0
8    6   0
4    5   6

Leave a Comment