Please explain to me what is going on in the following code, step by step and in
ID: 3726616 • Letter: P
Question
Please explain to me what is going on in the following code, step by step and in detail.
#include <stdio.h>
int main()
{
int i,j,q,w,sum,k;
int a[3][4] = { {3,1,2,4}, {1,1,2,2}, {0,4,7,2} };
int b[4][3] = { {3,1,2}, {1,1,2}, {0,4,7}, {3,5,7} };
int c[3][3],bb[3][4],cc[3][3];
for(i=0; i<3; i++)
{ for(j=0; j<4; j++)
{ printf("%d ", a[i][j]);
}
printf(" ");
}
printf(" ");
for(i=0; i<4; i++)
{ for(j=0; j<3; j++)
{ printf("%d ", b[i][j]);
}
printf(" ");
}
printf(" ");
//sum=0;
for(q=0; q<3; q++)
{ for(w=0; w<3; w++)
{sum=0;
for(k=0;k<4;k++)
{
sum =sum+a[q][k]*b[k][w];
}
c[q][w]=sum;
}
}
for(q=0; q<3; q++)
{ for(w=0; w<3; w++)
{ printf("%d ", c[q][w]);
}
printf(" ");
}
printf(" ");
for(j=0; j<3; j++)
for(i=0; i<4; i++)
bb[j][i] =b[i][j];
for(j=0; j<3; j++)
{ for(i=0; i<4; i++)
{ printf("%d ", bb[j][i]);
}
printf(" ");
}
printf(" ");
for(q=0; q<3; q++)
{ for(w=0; w<3; w++)
{sum=0;
for(k=0;k<4;k++)
{
sum =sum+a[q][k]*bb[w][k];
}
cc[q][w]=sum;
}
}
for(q=0; q<3; q++)
{ for(w=0; w<3; w++)
{ printf("%d ", cc[q][w]);
}
printf(" ");
}
printf(" ");
}
Explanation / Answer
I have explained in the code. Let me know if you are unclear with any line.
Output:
3 1 2 4
1 1 2 2
0 4 7 2
3 1 2
1 1 2
0 4 7
3 5 7
22 32 50
10 20 32
10 42 71
3 1 0 3
1 1 4 5
2 2 7 7
22 32 50
10 20 32
10 42 71
Explanation:
#include <stdio.h>
int main()
{
int i,j,q,w,sum,k;
int a[3][4] = { {3,1,2,4}, {1,1,2,2}, {0,4,7,2} }; #intializing 2-D matrix a
int b[4][3] = { {3,1,2}, {1,1,2}, {0,4,7}, {3,5,7} }; #intializing 2-D matrix a
int c[3][3],bb[3][4],cc[3][3]; ##declaring 3 2-D matrices
#This will print matrix a
for(i=0; i<3; i++)
{ for(j=0; j<4; j++)
{ printf("%d ", a[i][j]);
}
printf(" ");
}
printf(" ");
#This will print matrix b
for(i=0; i<4; i++) #loop form 0-3
{ for(j=0; j<3; j++)
{ printf("%d ", b[i][j]);
}
printf(" ");
}
printf(" ");
//sum=0;
# this loop is multiplying row element of matrix a to column element of matrix b and add result into sum.
for(q=0; q<3; q++)
{ for(w=0; w<3; w++)
{sum=0;
for(k=0;k<4;k++)
{
sum =sum+a[q][k]*b[k][w];
}
c[q][w]=sum;
}
}
#This will print matrix c
for(q=0; q<3; q++)
{ for(w=0; w<3; w++)
{ printf("%d ", c[q][w]);
}
printf(" ");
}
printf(" ");
#this loop will transpose b matrix and store it into bb
for(j=0; j<3; j++)
for(i=0; i<4; i++)
bb[j][i] =b[i][j];
#This will print matrix bb
for(j=0; j<3; j++)
{ for(i=0; i<4; i++)
{ printf("%d ", bb[j][i]);
}
printf(" ");
}
printf(" ");
# this loop is multiplying row element of matrix a to row element of matrix bb and add result into sum.
for(q=0; q<3; q++)
{ for(w=0; w<3; w++)
{sum=0;
for(k=0;k<4;k++)
{
sum =sum+a[q][k]*bb[w][k];
}
cc[q][w]=sum;
}
}
#This will print matrix cc
for(q=0; q<3; q++)
{ for(w=0; w<3; w++)
{ printf("%d ", cc[q][w]);
}
printf(" ");
}
printf(" ");
}