C Language Examples - Adding Two Matrices
Add two matrices using multidimensional arrays.
Example
#include
<
stdio.h
int
main
(
)
{
int
r
,
c
,
a
[
100
]
[
100
]
,
b
[
100
]
[
100
]
,
sum
[
100
]
[
100
]
,
i
,
j;
printf
(
"
Enter the number of rows (1 ~ 100):
"
)
;
scanf
(
"
%d
"
, &
r
)
;
printf
(
"
Enter the number of columns (1 ~ 100):
"
)
;
scanf
(
"
%d
"
, &
c
)
;
printf
(
"
\
nEnter the elements of the first array:
\
n
"
)
;
for
(
i
=
0
;
i
<
r
; ++
i
)
for
(
j
=
0
;
j
<
c
; ++
j
)
{
printf
(
"
Enter element a%d%d:
"
,
i
1
,
j
1
)
;
scanf
(
"
%d
"
,&
a
[
i
]
[
j
]
)
;
}
printf
(
"
Enter the elements of the second array:
\
n
"
)
;
for
(
i
=
0
;
i
<
r
; ++
i
)
for
(
j
=
0
;
j
<
c
; ++
j
)
{
printf
(
"
Enter element a%d%d:
"
,
i
1
,
j
1
)
;
scanf
(
"
%d
"
, &
b
[
i
]
[
j
]
)
;
}
// Add
for
(
i
=
0
;
i
<
r
;++
i
)
for
(
j
=
0;
j
<
c
;++
j
)
{
sum
[
i
]
[
j
]
=
a
[
i
]
[
j
]
b
[
i
]
[
j
];
}
// Display the result
printf
(
"
\
nResult of adding the two-dimensional arrays:
\
n
\
n
"
)
;
for
(
i
=
0
;
i
<
r
;++
i
)
for
(
j
=
0;
j
<
c
;++
j
)
{
printf
(
"
%d
"
,
sum
[
i
]
[
j
]
);
if
(
j
==
c
1
)
{
printf
(
"
\
n
\
n
"
)
;
}
}
return
0
;
}
The output is:
输入行数 ( 1 ~ 100): 2
输入列数 ( 1 ~ 100): 3
Enter elements of the first-dimensional array:
输入元素 a11: 2
输入元素 a12: 3
输入元素 a13: 4
输入元素 a21: 5
输入元素 a22: 2
输入元素 a23: 3
Enter elements of the second-dimensional array:
输入元素 a11: -4
输入元素 a12: 5
输入元素 a13: 3
输入元素 a21: 5
输入元素 a22: 6
输入元素 a23: 3
2D array addition result:
-2 8 7
10 8 6
C Language Examples