Kodewick
Start learning →
Starter←→0 / 50

Matrix diagonal sum

#038Starterm[i][i]5 min

In a 3×3 matrix (2D array m), the main diagonal runs top-left to bottom-right: 1 + 5 + 10 = 16; the other diagonal runs top-right to bottom-left: 3 + 5 + 7 = 15. With one loop, add the two diagonals into sum1 and sum2. The program shows 16 and 15, one per line.

Should show
16
15
main.c
#include <stdio.h>

int main(void) {
    int m[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 10}
    };
    int sum1 = 0, sum2 = 0;
    for (int i = 0; i < 3; i++) {
        // your code here: add row i of the main diagonal to sum1
        // your code here: add row i of the other diagonal to sum2
    }
    printf("%d\n", sum1);
    printf("%d\n", sum2);
    return 0;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.