Write a program that checks whether a matrix is an upper triangular matrix.
A matrx is said to be an upper triangular matrix if all values under the main diagonal are zeros.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define SIZE 50
void main()
{
int A[SIZE][SIZE];
int R, C; /* dimensions */
int I, J;
do {
printf("Number of rows (max.%d) : ", SIZE);
scanf("%d", &R);
} while (R <= 0 || R > SIZE);
do {
printf("Number of columns (max.%d) : ", SIZE);
scanf("%d", &C);
} while (C <= 0 || C > SIZE);
printf("*** Matrix ***\n");
for (I = 0; I<R; I++)
for (J = 0; J<C; J++)
{
printf("A[%d][%d] : ", I, J);
scanf("%d", &A[I][J]);
}
// check if the matrix is an upper triangular matrix
for (I = 0; I < R; I++)
{
// we check elements less than I
for (J = 0; J < I; J++)
if (A[I][J] != 0) // if one element is not zero, exit the innner loop
break;
if (J < I) // either we have exited the inner loop normally (J==I), nothing to do , we continue
break; // otherwise, we exited the loop because if the break, so we need to exit the outer loop too
}
if (I == R)
printf("The matrix is an Upper triangular matrix.\n");
else
printf("The matrix is not an Upper triangular matrix.\n");
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Add into a table based on hash coalesced with separated zones