Matrix is upper triangular or not
C program to check if matrix is upper triangular or not.
A square matrix is called upper triangular if all the entries below the main diagonal are zero.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void upp_tri(int mat[MAX][MAX], int row)
{
int i, j, flag;
flag = 0;
for(i=1;i<row;i++)
{
for(j=0;j<i;j++)
{
if(mat[i][j] != 0)
{
flag = 1;
}
}
}
if(flag == 0)
{
printf("\nMatrix is upper triangular");
}
else
{
printf("\nMatrix is not upper triangular");
}
}
void main()
{
int mat[MAX][MAX];
int row, col;
printf("Enter the number of rows or columns of the square matrix\t:");
scanf("%d",&row);
col = row;
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
upp_tri(mat, row);
getch();
}
Output
********** Run1 **********
Enter the number of rows or columns of the square matrix :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [1][0] :0
Element [1][1] :5
Element [1][2] :6
Element [1][3] :7
Element [2][0] :0
Element [2][1] :0
Element [2][2] :8
Element [2][3] :9
Element [3][0] :0
Element [3][1] :0
Element [3][2] :0
Element [3][3] :10
Matrix entered is
1 2 3 4
0 5 6 7
0 0 8 9
0 0 0 10
Matrix is upper triangular
********** Run2 **********
Enter the number of rows or columns of the square matrix :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [1][0] :0
Element [1][1] :5
Element [1][2] :6
Element [1][3] :7
Element [2][0] :0
Element [2][1] :8
Element [2][2] :9
Element [2][3] :10
Element [3][0] :0
Element [3][1] :0
Element [3][2] :0
Element [3][3] :11
Matrix entered is
1 2 3 4
0 5 6 7
0 8 9 10
0 0 0 11
Matrix is not upper triangular