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