This program adds two 2-D matrices of order m x n and displays the resultant matrix.
C Program
#include <stdio.h>
int main() {
int a[10][10], b[10][10], sum[10][10];
int m, n, i, j;
printf("Enter number of rows (m) and columns (n): ");
scanf("%d %d", &m, &n);
printf("Enter elements of first matrix:\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
printf("Enter elements of second matrix:\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &b[i][j]);
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum[i][j] = a[i][j] + b[i][j];
printf("Resultant matrix (sum):\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Explanation
- Both matrices must have the same dimensions (m rows, n columns) for element-wise addition to be valid.
- Nested loops read each matrix row by row, column by column.
- The sum matrix is built by adding corresponding elements:
sum[i][j] = a[i][j] + b[i][j]. - A final pair of nested loops prints the result, with a newline after each row so it displays as a proper grid.
Sample Output
Enter number of rows (m) and columns (n): 2 2
Enter elements of first matrix:
1 2
3 4
Enter elements of second matrix:
5 6
7 8
Resultant matrix (sum):
6 8
10 12