C Exercise Example 38
Title:Find the sum of diagonal elements of a 3*3 matrix
Program analysis:Use a double for loop to control the input of the two-dimensional array, then accumulate a[i][i] and output.
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
//
#include<stdio.h>
#define N 3
int main()
{
int i,j,a[N][N],sum=0;
printf("Please enter a matrix (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("Sum of diagonal elements is: %d\n",sum);
return 0;
}
The output result of the above example is:
请输入矩阵(3*3): 1 2 3 4 5 6 7 8 9 对角线之和为:15other extensions