Write a C program to find the sum of diagonal elements of a square matrix.
#include <stdio.h>
#define MAXROW 10
#define MAXCOL 10
int main() {
int mat[MAXROW][MAXCOL], sum = 0, i, j, order;
/* get the order of the input matrix from the user */
printf("Enter the order of the input matrix:");
scanf("%d", &order);
/* Boundary Check */
if (order < 0 || order > MAXROW) {
printf("Boundary Level Exceeded!!\n");
return 0;
}
/* get the entries of the input matrix */
printf("Enter the entries for the input matrix:\n");
for (i = 0; i < order; i++) {
for (j = 0; j < order; j++) {
scanf("%d", &mat[i][j]);
}
}
/* find the sum of diagonal elements */
for (i = 0; i < order; i++) {
for (j = 0; j < order; j++) {
if (i == j) {
sum = sum + mat[i][j];
}
}
}
/* print the results */
printf("Sum of the diagonals: %d\n", sum);
return 0;
}
#define MAXROW 10
#define MAXCOL 10
int main() {
int mat[MAXROW][MAXCOL], sum = 0, i, j, order;
/* get the order of the input matrix from the user */
printf("Enter the order of the input matrix:");
scanf("%d", &order);
/* Boundary Check */
if (order < 0 || order > MAXROW) {
printf("Boundary Level Exceeded!!\n");
return 0;
}
/* get the entries of the input matrix */
printf("Enter the entries for the input matrix:\n");
for (i = 0; i < order; i++) {
for (j = 0; j < order; j++) {
scanf("%d", &mat[i][j]);
}
}
/* find the sum of diagonal elements */
for (i = 0; i < order; i++) {
for (j = 0; j < order; j++) {
if (i == j) {
sum = sum + mat[i][j];
}
}
}
/* print the results */
printf("Sum of the diagonals: %d\n", sum);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the order of the input matrix:3
Enter the entries for the input matrix:
10 20 30
40 50 60
70 80 40
Sum of the diagonals: 100
Enter the order of the input matrix:3
Enter the entries for the input matrix:
10 20 30
40 50 60
70 80 40
Sum of the diagonals: 100
No comments:
Post a Comment