Monday 6 April 2015

Upper triangular matrix

Question: Program to print the upper triangular matrix.

To print the upper triangle 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 UprTrn  
  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.             matA[row,col]= Convert.ToInt16(Console.ReadLine());  
  20.   
  21.             Console.WriteLine();  
  22.         }  
  23.   
  24.         Console.WriteLine("\nMatrix A: ");  
  25.         for(row=0; row<i; row++)  
  26.         {  
  27.             for(col = 0; col<j; col++)  
  28.             Console.Write("{0:D2} ", matA[row,col]);  
  29.   
  30.             Console.WriteLine();  
  31.         }  
  32.   
  33.         Console.WriteLine("\nUpper triangle of Matrix A:");  
  34.         for(row=0;row<i; row++)  
  35.         {  
  36.             for(col=0;col<j; col++)  
  37.             {  
  38.                   
  39.                 matA[row,col] = (row<=col)? matA[row,col] : 0;  
  40.   
  41.                 Console.Write("{0} ",matA[row,col]);  
  42.             }  
  43.   
  44.             Console.WriteLine();  
  45.         }  
  46.   
  47.         Console.ReadLine();  
  48.           
  49.     }  
  50. } 
** Complete code

Logic:

To print the upper triangular matrix we check the no. of current row and column is the no. of current row is greater that the no. of column than 0 will be printed other wise matrix remain as it is.

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


Screenshot:

Image of upper triangular matrix
Upper triangular matrix