Write a program that checks whether a matrix is a lower triangular matrix.
A matrx is said to be a lower triangular matrix if all values above 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 a lower triangular matrix
for (I = 0; I < R; I++)
{
// we check elements greater than I
for (J = I+1; J < R; J++)
if (A[I][J] != 0) // if one element is not zero, exit the inner loop
break;
if (J < R) // either we have exited the inner loop normally (J==R), 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 a Lower triangular matrix.\n");
else
printf("The matrix is not a Lower triangular matrix.\n");
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Printing a sequence of instructions on a machine with 1 register and 6 instructions