In: Computer Science
The third worksheet ("Ex. 3") contains 2 4x4 matrices, plus space for a third. Write a program that will read the first 2 matrices into array "B" and "C" . Create a 3rd array, "A" that is the result of matrix B + matrix C (i.e |A| = |B| + |C|). Output that array in the indicated cells (upper left = cell K1) To do this, use the rule for array addition for each matrix element: aij = bij + cij where i and j indicate the location (row, column) of the matrix element. NOTE: You must use arrays to get credit for this exercise. Keep close track of which loop is representing which index.
74 | 21 | 95 | 8 | 16 | 30 | 40 | 5 | ||||||
52 | 79 | 41 | 23 | + | 33 | 8 | 32 | 5 | = | ||||
3 | 91 | 33 | 37 | 24 | 4 | 4 | 12 | ||||||
93 | 68 | 40 | 74 | 24 | 27 | 24 | 15 |
The program is basically keeping a track of addition of each element corresponding to the same indexes i,j and storing them in a third array of same size.
so, let us first understand the concept of array addition
Our program will basically add all the elements corresponding to i=1 i.e j=1,2,3,4 i.e 4 iterations. After the completion of i=1, it will move on to 2,3,4 respectively and add its iterations as well
As the language is not specified, for the comfort of students, I will be using basic C code.
*******************************************************************************************************************
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j,k,s=0;
int a[4][4], b[4][4], c[4][4]; //declaring the three 4*4 arrays
//getting the input for array b
for(i=0;i<4;i++)
{for(j=0;j<4;j++)
{
scanf("%d",&b[i][j]);
}
}
//getting the input for array c
for(i=0;i<4;i++)
{for(j=0;j<4;j++)
{
scanf("%d",&c[i][j]);
}
}
//adding the corresponding elements of b and c and storing it in a
for(i=0;i<4;i++)
{for(j=0;j<4;j++)
{
a[i][j]=b[i][j]+c[i][j];
}
}
}
**************************************************************************************************************
An array always store values from 0,0 index, so our code will work upon 0,1,2,3 and its corresponding 4 iterations.
Now let us look for loop iterations.
loop 1 i=0:
i=0,j=0: 74+16
i=0,j=1: 21+30
i=0,j=2: 95+40
i=0,j=3: 8+5
loop 2 i=1:
i=1,j=0: 52+33
i=1,j=1: 79+8
i=1,j=2: 41+32
i=1,j=3: 23+5
loop 3 i=2:
i=2,j=0: 3+24
i=2,j=1:91+4
i=2,j=2:33+4
i=2,j=3:97+12
loop 4 i=3:
i=3,j=0: 93+24
i=3,j=1: 68+27
i=3,j=2: 40+24
i=3,j=3: 74+15
Therefore the final array A becomes
90 | 51 | 135 | 31 |
85 | 87 | 73 | 28 |
27 | 95 | 37 | 109 |
117 | 95 | 64 | 89 |