Adding two matrix
Here we are writing a code in C to find the sum of two matrices.
Matrix C indicates the sum of matrix A and B.
Video Tutorial:
First of all, we will initialize three two dimensional arrays and two other variables 'i' and 'j'
int row, col, a[10][10], b[10][10], c[10][10],i, j;
Then we will take the input for the number of rows and columns for both the matrices, as for this program both the matrix 'a' and 'b' will have the same number of rows and columns.
scanf("%d %d", &row, &col);
The 'a' and 'b' arrays are the input that the user will give to the given program.
Now after this we will use the for loop with 'i' and 'j' to put the numbers into the rows and columns for both the matrix 'a' provided in the program here.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
scanf("%d", &a[i][j]);
}
Again we will use the for loop with 'i' and 'j' to put the numbers into the rows and columns for both the matrix 'a' provided in the program here.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
scanf("%d", &b[i][j]);
}
Now, we will again use the for loop using 'i' and 'j' variable to add these two matrices 'a' and 'b', and store the result into a third matrix 'c' which we assigned in above steps here.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
c[i][j]=a[i][j]+b[i][j];
}
Now after this we will use the for loop with 'i' and 'j' to put the numbers into the rows and columns for both the matrix 'c' provided in the program here. We will use the 'c' matrix tho store our output i.e. the sum of 'a' and 'b' matrices, and finally, it will be printed as the output
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
printf("%d", c[i][j]);
printf("\n");
}
Here in our program we will take 'a' matrix as:
1 2
3 4
and 'b' matrix also as:
1 2
3 4
Now the first element of the first row of both the matrix will be added i.e 1+1 = 2 which will the first element of the first row of the output matrix 'c'.
Now the second element of the first row of both the matrix will be added i.e 2+2 = 4 which will the second element of the first row of the output matrix 'c'.
Now the first element of the second row of both the matrix will be added i.e 3+3 = 6 which will the first element of the second row of the output matrix 'c'.
Now the second element of the first row of both the matrix will be added i.e 4+4 = 8 which will the first element of the second row of the output matrix 'c'.
So, the sum of the matrices 'a' and 'b' which is stored in 'c' will give the output:
2 4
6 8
0 Comments