Tuesday 7 April 2015

Lower Triangular matrix

Question: Program to print the lower triangular matrix.

To print the Lower Triangle of the matrix first of all take the order of matrix it must be square, so, number of row and column oh the matrix is same, after that enter the element of the matrix after that print the matrix on the console.

Code Snippet:


  1. using System;  
  2. public class LowTrn  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         int i, j, row, col;  
  7.         int[,] matA = new int[10,10];  
  8.           
  9.         Console.Write("\nEnter the no. of row: ");  
  10.         i=Convert.ToInt16(Console.ReadLine());  
  11.   
  12.         Console.Write("Enter the no. of col: ");  
  13.         j=Convert.ToInt16(Console.ReadLine());  
  14.   
  15.         Console.WriteLine("\nEnter the Element in Matrix: ");  
  16.         for(row=0; row<i; row++)  
  17.         {  
  18.             for(col = 0; col<j; col++)  
  19.             {  
  20.                 Console.Write("Matrix A[{0},{1}]: ", row, col);  
  21.                 matA[row,col]= Convert.ToInt16(Console.ReadLine());  
  22.             }  
  23.   
  24.             Console.WriteLine();  
  25.         }  
  26.   
  27.         Console.WriteLine("\nMatrix A: ");  
  28.         for(row=0; row<i; row++)  
  29.         {  
  30.             for(col = 0; col<j; col++)  
  31.             Console.Write("{0:D2} ", matA[row,col]);  
  32.   
  33.             Console.WriteLine();  
  34.         }  
  35.         Console.ReadLine();  
  36.   
  37.         Console.WriteLine("\nLower triangle of Matrix A:");  
  38.         for(row=0;row<i; row++)  
  39.         {  
  40.             for(col=0;col<j; col++)  
  41.             {  
  42.                   
  43.                 matA[row,col] = (row < col)? 0 : matA[row,col];  
  44.   
  45.                 Console.Write("{0} ",matA[row,col]);  
  46.             }  
  47.   
  48.             Console.WriteLine();  
  49.         }  
  50.   
  51.         Console.ReadLine();  
  52.           
  53.     }  
** Complete code

Logic:

  1. for(row=0;row<i; row++)  
  2.         {  
  3.             for(col=0;col<j; col++)  
  4.             {  
  5.                   
  6.                 matA[row,col] = (row < col)? 0 : matA[row,col];  
  7.   
  8.                 Console.Write("{0} ",matA[row,col]);  
  9.             }  
  10.   
  11.             Console.WriteLine(); 

Description:

In the above, if the number of column is greater than the row than 0 will be print other wise element of the matrix remain same as it is.


Screenshot:

image of Lower triangle of matrix
Lower triangle of matrix

Read Also: