Answer to Question #287851 in C for sunshine

Question #287851

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


1
Expert's answer
2022-01-16T04:16:41-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS