C Program to Add Two Matrices using Multi-Dimensional Arrays
C program to add two matrices using multi-dimensional arrays.
In this article, you will learn how to make sum of the two multi-dimensional arrays.
Example
Enter No. of Row & Column:
2
3
Enter the values of the first matrix - matrix_1
Enter value - M1[0][0]: 5
Enter value - M1[0][1]: 9
Enter value - M1[0][2]: 6
Enter value - M1[1][0]: 3
Enter value - M1[1][1]: 6
Enter value - M1[1][2]: 1
Enter the values of the first matrix - matrix_1
Enter value - M2[0][0]: 8
Enter value - M2[0][1]: 7
Enter value - M2[0][2]: 4
Enter value - M2[1][0]: 3
Enter value - M2[1][1]: 9
Enter value - M2[1][2]: 7
SUM of two matrices matrix_1 & matrix_2
13 16 10
6 15 8
You should have knowledge of the following topics in c programming to understand this program:
- C For Loop
- C Arrays
Source
// C program to add two Matrices using Multi-dimensional Arrays
#include <stdio.h>
// It's main function of the program
int main() {
int rows, columns;
printf("Enter No. of Row & Column:\n");
scanf("%d %d", &rows, &columns);
int matrix_1[rows][columns];
int matrix_2[rows][columns];
int matrix_sum[rows][columns];
// Step-1 Enter the values of first matrix
printf("\nEnter the values of the first matrix - matrix_1\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("Enter value - M1[%d][%d]: ", i, j);
scanf("%d", &matrix_1[i][j]);
}
}
// Step-1 Enter the values of second matrix
printf("\nEnter the values of the second matrix - matrix_1\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("Enter value - M2[%d][%d]: ", i, j);
scanf("%d", &matrix_2[i][j]);
}
}
// Step-3 Add the matrices M1 & M2 and store these values in another matrices `matrix_sum`
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix_sum[i][j] = matrix_1[i][j] + matrix_2[i][j];
}
}
// Step-4 Final output of the program to print the final matrices
printf("\nSUM of two matrices matrix_1 & matrix_2\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d\t", matrix_sum[i][j]);
}
printf("\n");
}
return 0;
}
Output
Enter No. of Row & Column:
3
4
Enter the values of the first matrix - matrix_1
Enter value - M1[0][0]: 12
Enter value - M1[0][1]: 4
Enter value - M1[0][2]: 6
Enter value - M1[0][3]: 7
Enter value - M1[1][0]: 20
Enter value - M1[1][1]: 3
Enter value - M1[1][2]: 6
Enter value - M1[1][3]: 80
Enter value - M1[2][0]: 45
Enter value - M1[2][1]: 25
Enter value - M1[2][2]: 60
Enter value - M1[2][3]: 10
Enter the values of the first matrix - matrix_1
Enter value - M2[0][0]: 10
Enter value - M2[0][1]: 20
Enter value - M2[0][2]: 30
Enter value - M2[0][3]: 90
Enter value - M2[1][0]: 70
Enter value - M2[1][1]: 50
Enter value - M2[1][2]: 45
Enter value - M2[1][3]: 80
Enter value - M2[2][0]: 14
Enter value - M2[2][1]: 23
Enter value - M2[2][2]: 45
Enter value - M2[2][3]: 92
SUM of two matrices matrix_1 & matrix_2
22 24 36 97
90 53 51 160
59 48 105 102