Write a C program to check whether a matrix is diagonal.
#include <stdio.h>
#define MAXROWS 10
#define MAXCOLS 10
int main() {
int i, j, row, col, flag = 0;
int matrix[MAXROWS][MAXCOLS];
/* get the number of rows from the user */
printf("Enter the number of rows:");
scanf("%d", &row);
/* get the number of columns from the user */
printf("Enter the number of columns:");
scanf("%d", &col);
/* Boundary Check */
if (row > MAXROWS || row < 0 || col > MAXCOLS || col < 0) {
printf("Boundary Level Exceeded!!\n");
return 0;
}
/* get the entries for the input matrix */
printf("\nEnter the matrix entries:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
scanf("%d", &matrix[i][j]);
}
}
#define MAXROWS 10
#define MAXCOLS 10
int main() {
int i, j, row, col, flag = 0;
int matrix[MAXROWS][MAXCOLS];
/* get the number of rows from the user */
printf("Enter the number of rows:");
scanf("%d", &row);
/* get the number of columns from the user */
printf("Enter the number of columns:");
scanf("%d", &col);
/* Boundary Check */
if (row > MAXROWS || row < 0 || col > MAXCOLS || col < 0) {
printf("Boundary Level Exceeded!!\n");
return 0;
}
/* get the entries for the input matrix */
printf("\nEnter the matrix entries:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
scanf("%d", &matrix[i][j]);
}
}
/* checking for diagonal matrix */
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
if (i != j && matrix[i][j] != 0) {
flag = 1;
goto end;
}
}
}
end:
/* printing the result */
if (flag) {
printf("Given Matrix is not a diagonal matrix!!\n");
} else {
printf("Given Matrix is a diagonal matrix!!\n");
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of rows:3
Enter the number of columns:3
Enter the matrix entries:
10 00 00
00 10 00
00 00 11
Given Matrix is a diagonal matrix!!
Enter the number of rows:3
Enter the number of columns:3
Enter the matrix entries:
10 00 00
00 10 00
00 00 11
Given Matrix is a diagonal matrix!!
mat[i][j]==0 in that if statement since diagonal matrix means all the elements except diagonal elements are equal to zero
ReplyDeleteExactly! I was wondering About That ! All The Elements Other Than The Diagonal Elements Are Zeroes
Delete