Print lower triangular and upper triangular matrix in C++

In this tutorial, we are going to learn how to print lower triangular and upper triangular matrix in C++.

  • A lower triangular matrix is a matrix which lies below the main diagonal. It includes the main diagonal and rest of elements are 0.
  • An upper triangular matrix is a matrix which lies above the main diagonal. It includes the main diagonal and rest of elements are 0.

Lower triangular matrix:

A 0 0 0
B c 0 0
D E F 0
G H I J

Upper triangular matrix:

A B C D
0 E F G
0 0 H I
0 0 0 J

For the lower triangular matrix, we will check row and column respectively. If the row position is lower than column position we simply make that position 0.

For the upper triangular matrix, we will check row and column respectively. If row position is greater than column position we simply make that position 0.

Now let us try to implement it in our code.

Code to print lower triangular and upper triangular matrix in C++

Cpp source code:

// Code to print lower triangular and upper triangular matrix
#include<bits/stdc++.h> 
using namespace std; 

int main() 
{ 
    int row,column;
    cout<<"Enter row and column: ";
  cin>>row>>column;
  int matrix[row][column];
  cout<<"\nEnter matrix elements:\n";
  for(int i=0;i<row;i++)
  {
    for(int j=0;j<column;j++)
    {
      cin>>matrix[i][j];
    }
  }
  cout<<"\n";
  // printing lower triangular matrix
  cout << "Lower triangular matrix: \n"; 
  for (int i = 0; i < row; i++) 
  { 
    for (int j = 0; j < column; j++) 
    { 
      if (i < j) 
      { 
        cout << "0" << " "; 
      } 
      else
      cout << matrix[i][j] << " "; 
    } 
    cout << endl; 
  } 
  
  // printing upper triangular matrix
  cout << "Upper triangular matrix: \n";
  for (int i = 0; i < row; i++) 
  { 
    for (int j = 0; j < column; j++) 
    { 
      if (i > j) 
      { 
        cout << "0" << " "; 
      } 
      else
      cout << matrix[i][j] << " "; 
    } 
    cout << endl; 
  }	
  return 0; 
}

Input/Output:

Enter row and column: 4 4

Enter matrix elements:
11 12 13 14
15 16 17 18
19 20 21 22
23 24 25 26

Lower triangular matrix:
11 0  0  0
15 16 0  0
19 20 21 0
23 24 25 26
Upper triangular matrix:
11 12 13 14
0  16 17 18
0  0  21 22
0  0  0  26

You may also learn:

How to add all the diagonal elements of a matrix in C++

How to sort a Matrix in C++

Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.

Leave a Reply

Your email address will not be published. Required fields are marked *