Write a C program that creates a 4x4 2d array, fill it with user-defined values and display (separately) the sum of the diagonal as well as the upper and lower triangular elements.
d ut ut ut
Lt d ut ut
Lt Lt d ut
Lt Lt Lt d
where: ut means upper triangular
Lt means lower triangular
d means diagonal elements
#include <stdio.h>
#define N 4
int main() {
double Mat[N][N];
double upper, lower, diagonal;
for (int i=0; i<N; i++) {
printf("Please enter %d values for %d-th row\n", N, i+1);
for (int j=0; j<N; j++) {
scanf("%lf", &Mat[i][j]);
}
}
printf("\n");
upper = lower = diagonal = 0.0;
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
if (j > i) {
upper += Mat[i][j];
}
else if (j < i) {
lower += Mat[i][j];
}
else { // j == i
diagonal += Mat[i][j];
}
}
}
printf("Sum of diagonal elements is %lf\n", diagonal);
printf("Sum of upper triangular elements is %lf\n", upper);
printf("Sum of lower triangular elements is %lf\n", lower);
return 0;
}
Comments
Leave a comment