Site icon T4Tutorials.com

Write a C++ program to print the lower and upper triangles of a square matrix

Write a C++ program to print the lower and upper triangles of a square matrix.

#include<bits/stdc++.h> 
using namespace std; 
int main() 
{ 
    int ROWS,COLUMNS;
    cout<<"Please Enter ROWS and COLUMNS: ";
  cin>>ROWS>>COLUMNS;
  int T4Tutorials[ROWS][COLUMNS];
  cout<<"\nPlease Enter matrix elements:\n";
  for(int Loop1=0;Loop1<ROWS;Loop1++)
  {
    for(int Loop2=0;Loop2<COLUMNS;Loop2++)
    {
      cin>>T4Tutorials[Loop1][Loop2];
    }
  }
  cout<<"\n";
  // printing lower triangular matrix
  cout << "Lower triangular matrix: \n"; 
  for (int Loop1 = 0; Loop1 < ROWS; Loop1++) 
  { 
    for (int Loop2 = 0; Loop2 < COLUMNS; Loop2++) 
    { 
      if (Loop1 < Loop2) 
      { 
        cout << "0" << " "; 
      } 
      else
      cout << T4Tutorials[Loop1][Loop2] << " "; 
    } 
    cout << endl; 
  } 
  
  // printing upper triangular matrix
  cout << "Upper triangular matrix: \n";
  for (int Loop1 = 0; Loop1 < ROWS; Loop1++) 
  { 
    for (int Loop2 = 0; Loop2 < COLUMNS; Loop2++) 
    { 
      if (Loop1 > Loop2) 
      { 
        cout << "0" << " "; 
      } 
      else
      cout << T4Tutorials[Loop1][Loop2] << " "; 
    } 
    cout << endl; 
  }  
  return 0; 
}

Output

C++ lower and upper triangles of a square matrix
C++ lower and upper triangles of a square matrix
Exit mobile version