C language: Find the sum of the diagonal elements of a 3*3 matrix

#include<stdio.h>
#define n 3
int main()
{
    int i,j,a[n][n],sum=0;
    printf("请输入矩阵(3*3):\n");
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%d",&a[i][j]);
    for(i=0;i<n;i++)
        sum+=a[i][i];
    printf("对角线之和为:%d\n",sum);
    return 0;
}

Use the define function to define n at the beginning to make the program more concise and clear. Use double for loops to input the matrix and solve it.

If you have any questions, please discuss them below, and I will answer them for you .

Guess you like

Origin blog.csdn.net/samxiaoguai/article/details/78578156