C Program to add two matrix.
Objective
Write a C program to add two 2D Matrices.
Algorithm / Approach
- Declare three 3x3 matrices:
m1,m2, andm3. - Use nested loops (rows
i, columnsj) to read data intom1andm2. - Use nested loops to add the matrices mathematically:
m3[i][j] = m1[i][j] + m2[i][j]. - Print the resulting
m3matrix.
main.c
#include<stdio.h>
int main( ) {
int r=3, c=3, i, j ;
int m1[3][3], m2[3][3],m3[3][3];
printf("Enter elements of mat1: ");
for(i=0; i < r; i++){
for(j=0; j < c; j++){
scanf("%d", &m1[i][j]);
}
}
printf("Enter elements of mat2: ");
for(i=0; i < r; i++){
for(j=0 ; j < c; j++){
scanf("%d", &m2[i][j]);
}
}
printf("Sum of Matrix :\n");
for(i=0; i < r; i++) {
for(j=0 ; j < c; j++) {
m3[i][j] = m1[i][j]+m2[i][j];
printf("%d ", m3[i][j]);
}
printf("\n");
}
return 0;
}
Expected Output
Enter the elements of mat1 : 1 2 3 2 3 4 1 5 4 Enter the elements of mat2 : 6 5 3 3 4 5 6 5 3 Sum of Matrix : 7 7 6 5 7 9 7 10 7
Explanation of the Program
- A 2D array (matrix) is essentially an array of arrays. The first index represents the row, and the second represents the column.
- Matrix addition is straightforward: you simply add the elements that share the exact same coordinates (e.g., Row 0 Col 0 of M1 + Row 0 Col 0 of M2).
Complexity
Time Complexity
O(r * c) - Where r is rows and c is columns.
Space Complexity
O(r * c) - For storing the 3 matrices.