This is a C++ Program to Find if an Array is a Triangular Matrix.
The program takes a matrix and checks if it is a triangular matrix. A triangular matrix is a square matrix which has all elements above or below the main diagonal as 0.
1. The program takes the number of rows and columns of the matrix.
2. If they are not equal, it is not a square matrix. The program is exited.
3. Else, the matrix is checked if elements above or below teh main diagonal are zero.
4. The result is printed.
5. Exit.
Here is the source code of C++ Program to Find if an Array is a Triangular Matrix. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
int i, j, m, n, ut = 0, lt = 0, A[10][10];
cout << "Enter number of rows and columns : ";
cin >> m >> n;
if (m != n)
{
cout << "Matrix is not a square matrix!";
exit(0);
}
cout << "Enter elements of matrix : ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cin >> A[i][j];
if( j > i && A[i][j] != 0)
ut = 1;
if( j < i && A[i][j] != 0)
lt = 1;
}
}
if( ut == 0 || lt == 0)
cout << "The given matrix is a triangular matrix.\n ";
else
cout << "The given matrix is not a triangular matrix.\n ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
cout << A[i][j] << " ";
cout << "\n ";
}
return 0;
}
1. The user is asked to enter the number of rows and columns.
2. If they are not equal, the array is not a square matrix, hence it cannot be a triangular matrix. The program is exited.
3. Else, the elements are asked to enter and stored in ‘A’. The variables ‘ut’ and ‘lt’ are initialized as 0.
4. The elements below and above the main diagonal in the matrix are checked using ut and lt.
5. If elements above the diagonal are not 1, then ut is equal to 1, else if elements below diagonal are not 0 then lt is 1.
6. If either ut or lt is equal to 0, then the matrix is triangular. It may be upper triangular or lower triangular matrix.
7. Else the entered array is not a triangular matrix.
8. The result is then printed.
Case 1 : Enter number of rows and columns : 3 3 Enter elements of matrix : 1 2 3 0 4 5 0 0 6 The given matrix is a triangular matrix. 1 2 3 0 4 5 0 0 6 Case 2 : Enter number of rows and columns : 3 1 Matrix is not a square matrix! Case 3 : Enter number of rows and columns : 2 2 Enter elements of matrix : 1 2 3 4 The given matrix is not a triangular matrix. 1 2 3 4
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Check Computer Science Books
- Practice Computer Science MCQs
- Apply for C++ Internship
- Practice Programming MCQs
- Apply for Computer Science Internship