Example 61: Find the sum of diagonal elements of a 3*3 integer matrix in C language.
Problem-solving idea: The result of running an integer array used in the program is correct. If you are using a real array, you only need to change the int in line 4 of the program to double. When you are required to input data, you can enter a single-precision or double-precision number. To find the sum of 3*3 diagonal elements, it is Each row corresponds to the sum of the number of rows.
Source code demo:
#include<stdio.h>//头文件
int main()//主函数
{
int array[3][3],sum=0;//定义二维数组和变量
int i,j;//定义整型变量,主要用于for循环
printf("输入数据:\n");//提示语句
for(i=0;i<3;i++)//外层循环
{
for(j=0;j<3;j++)//内层循环
{
scanf("%3d",&array[i][j]);//键盘录入数据
}
}
for(i=0;i<3;i++)//循环
{
sum=sum+array[i][i];//求对角线上的数之和
}
printf("sum=%d\n",sum);//输出结果
return 0;//主函数返回值为0
}
The compilation and running results are as follows:
输入数据:
1 2 3
4 5 6
7 8 9
sum=15
--------------------------------
Process exited after 10.98 seconds with return value 0
请按任意键继续. . .
Readers think about how to change the code of the 5*5 matrix?
Find the sum of the diagonal elements of a 3*3 matrix in C language. For
more cases, you can go to the public account: C language entry to proficient