📊Beginner

Add Two Matrices

Matrix addition

Matrix Addition: Add corresponding elements of two matrices of the same size. C[i][j] = A[i][j] + B[i][j]

Program Code

matrix_add.c
C
1#include <stdio.h>
2
3int main() {
4 int rows = 2, cols = 3;
5
6 int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
7 int B[2][3] = {{7, 8, 9}, {10, 11, 12}};
8 int C[2][3];
9
10 // Add matrices
11 for (int i = 0; i < rows; i++) {
12 for (int j = 0; j < cols; j++) {
13 C[i][j] = A[i][j] + B[i][j];
14 }
15 }
16
17 printf("Matrix A:\n");
18 for (int i = 0; i < rows; i++) {
19 for (int j = 0; j < cols; j++)
20 printf("%3d ", A[i][j]);
21 printf("\n");
22 }
23
24 printf("\nMatrix B:\n");
25 for (int i = 0; i < rows; i++) {
26 for (int j = 0; j < cols; j++)
27 printf("%3d ", B[i][j]);
28 printf("\n");
29 }
30
31 printf("\nSum (A + B):\n");
32 for (int i = 0; i < rows; i++) {
33 for (int j = 0; j < cols; j++)
34 printf("%3d ", C[i][j]);
35 printf("\n");
36 }
37
38 return 0;
39}
Output

Matrix A:

1 2 3

4 5 6

 

Matrix B:

7 8 9

10 11 12

 

Sum (A + B):

8 10 12

14 16 18