Sum Matrix Diagonals in C

To find the sum of the diagonal elements of a matrix using the C language, you can write a simple program. Here is an example code:

#include <stdio.h>

int main() {
    int matrix[3][3] = {{1, 2, 3},
                        {4, 5, 6},
                        {7, 8, 9}};
    
    int sum = 0;
    for (int i = 0; i < 3; i++) {
        sum += matrix[i][i]; // 左上到右下对角线元素之和
        sum += matrix[i][2-i]; // 左下到右上对角线元素之和
    }

    printf("对角线元素之和为: %d\n", sum);

    return 0;
}

In the example above, we create a 3×3 matrix and use two for loops to iterate through the diagonal elements of the matrix. Finally, we calculate the sum and output the result. Feel free to modify the size and content of the matrix as needed.

bannerAds