Program to perform sum of two matrices.
Solution in C PYTHON
#include<stdio.h>
int main() {
int mtrx1[10][10], mtrx2[10][10], sum[10][10];
int row1, col1, row2, col2, i, j;
//Read size of first matrix
scanf("%d %d",&row1,&col1);
//Read size of second matrix
scanf("%d %d",&row2,&col2);
//Read matrix1 elements
for(i=0;i<row1;i++)
for(j=0;j<col1;j++)
scanf("%d",&mtrx1[i][j]);
for(i=0;i<row2;i++)
for(j=0;j<col2;j++)
scanf("%d",&mtrx2[i][j]);
//To perform addition between two matrices
//Number of rows of two matrices should be equal and
//Number of columns of two matrices should be equal
if(row1==row2 && col1==col2){
for(i=0;i<row1;i++)
for(j=0;j<col1;j++)
sum[i][j] = mtrx1[i][j] + mtrx2[i][j];
for(i=0;i<row1;i++){
for(j=0;j<col1;j++){
printf("%d ",sum[i][j]);
}
printf("\n");
}
}else{
printf("Matrices addition is impossible");
}
return 0;
}
int main() {
int mtrx1[10][10], mtrx2[10][10], sum[10][10];
int row1, col1, row2, col2, i, j;
//Read size of first matrix
scanf("%d %d",&row1,&col1);
//Read size of second matrix
scanf("%d %d",&row2,&col2);
//Read matrix1 elements
for(i=0;i<row1;i++)
for(j=0;j<col1;j++)
scanf("%d",&mtrx1[i][j]);
for(i=0;i<row2;i++)
for(j=0;j<col2;j++)
scanf("%d",&mtrx2[i][j]);
//To perform addition between two matrices
//Number of rows of two matrices should be equal and
//Number of columns of two matrices should be equal
if(row1==row2 && col1==col2){
for(i=0;i<row1;i++)
for(j=0;j<col1;j++)
sum[i][j] = mtrx1[i][j] + mtrx2[i][j];
for(i=0;i<row1;i++){
for(j=0;j<col1;j++){
printf("%d ",sum[i][j]);
}
printf("\n");
}
}else{
printf("Matrices addition is impossible");
}
return 0;
}
Input
3 3
3 3
1 1 1
1 1 1
1 1 1
0 1 1
2 0 1
2 2 0
Output
1 2 2
3 1 2
3 3 1
3 3
3 3
1 1 1
1 1 1
1 1 1
0 1 1
2 0 1
2 2 0
Output
1 2 2
3 1 2
3 3 1