Array Matrix Multiplication: How to perform Matrix multiplication using a 2D Array.

Learn 2D array manipulation and perform Matrix Multiplication in 2D Array. Learn Matrix multiplication by reading this blog, get the Algorithm and the code!

Algorithm

STEP 1: START
STEP 2: IF(COL1 != ROW2) THEN
STEP 3: PRINT('MULTIPLICATION NOT POSSIBLE')
STEP 4: EXIT
STEP 5: ELSE
STEP 6: FOR I=1 TO ROW1 DO
STEP 7: FOR J=1 TO COL2 DO
STEP 8: C[I][J]=0
STEP 9: FOR K=1 TO COL1 DO 
STEP 10: C[I][J]=C[I][J]+(A[I][K]+B[K][J])
STEP 11: ENDFOR
STEP 12: ENDFOR
STEP 13: ENFOR
STEP 14 END

Code

#include <stdio.h>
int a[3][3],b[3][3],c[3][3];
int n;
int input();
int printing();
int multiply();
int transpose();
int sub();
int add();
int main()
{
do{
printf("ENTER 1 for addition 2 for subtraction 3 for 
multiplication 4 for transpose and 0 for exit");
scanf("%d",&n);
switch(n){
case 1:
input();
add();
printf("sum of matrix: \n");
printing();
break;
case 2:
input();
sub();
printing();
break;
case 3:
input();
multiply();
printing();
break;
case 4:
input();
transpose();
printing();
break;
default:
printf("wrong choice");
}
}while(n!=0);
}
int printing(){
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}
int input(){
printf("ENTER THE ELEMENTS");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{ if(n==4){
printf("a[%d][%d]",i,j);
scanf("%d",&a[i][j]);
}
else{
printf("a[%d][%d]",i,j);
scanf("%d",&a[i][j]);}
printf("b[%d][%d]",i,j);
scanf("%d",&b[i][j]);
}
}
printf("matrix 1 \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("matrix 2 \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf("%d ",b[i][j]);
}
printf("\n");
}
return 0;
}
int add()
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
return 0;
}
int sub()
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]-b[i][j];
}
}
return 0;
}
int multiply()
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{ c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
return 0; 
}
int transpose(){
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[j][i];
}
}
return 0;
}

Output

$: ENTER 1 for addition 2 for subtraction 3 for multiplication 4 for 
transpose and 0 for exit3
ENTER THE ELEMENTSa[0][0]3
b[0][0]2
a[0][1]3
b[0][1]4
a[0][2]5
b[0][2]4
a[1][0]3
b[1][0]4
a[1][1]3
b[1][1]4
a[1][2]5
b[1][2]3
a[2][0]4
b[2][0]5
a[2][1]3
4b[2][1]
5
a[2][2]3
b[2][2]4
matrix 1
3 3 5
3 3 5
4 3 3
matrix 2
2 4 4
4 4 3
5 5 4
43 49 41
43 49 41
35 43 37
ENTER 1 for addition 2 for subtraction 3 for multiplication 4 for
transpose and 0 for exit0
wrong choice

Click here to get the algorithm and the code for merging two arrays.

Click here to get the algorithm and the code for inserting elements in an array.

Click here to get the algorithm and the code for the Linked List traversal

Leave a Comment

Your email address will not be published. Required fields are marked *