C++ Program to Print Upper and Lower Triangle of Matrix
Write C++ Program to Print Upper and Lower Triangle of Matrix
// CPP Program to Print Upper and Lower Triangle of Matrix
#include <iostream>
using namespace std;
void print_uppertriangle(int A[3][3],int i,int j)
{
for(i = 0; i < 3; i++) //to print the upper triangle
{
for(j = 0; j < 3;j ++)
{
if(i <= j)
{
cout << A[i][j] << " ";
}
else
{
cout << 0 << " ";
}
cout << " " ;
}
cout << endl;
}
}
void print_lowertriangle(int A[3][3],int i,int j)
{
for(i = 0; i < 3; i++) //to print the upper triangle
{
for(j = 0; j < 3; j++)
{
if(i >= j)
{
cout << A[i][j] << " ";
}
else
{
cout << 0 << " ";
}
cout << " ";
}
cout << endl;
}
}
int main()
{
int i,j;
int A[3][3] = {{2, 1, 6}, {9, 5, 1}, {4, 3, 8} };
cout << "Matrix A :--> \n";
for(i = 0;i < 3; i++)
{
for( j = 0; j < 3; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
cout << "\nUpper Triangular Matrix :--> \n";
print_uppertriangle(A, i, j);
cout << "\nLower Triangular Matrix :--> \n";
print_lowertriangle(A, i, j);
return 0;
}
Output:
Matrix A :-->
2 1 6
9 5 1
4 3 8
Upper Triangular Matrix :-->
2 1 6
0 5 1
0 0 8
Lower Triangular Matrix :-->
2 0 0
9 5 0
4 3 8