Programming Examples
C program to multiply two matrices
Write a program to input two matrix of size 3x3 and multiply two matrices in another third matrix.
Solution
#include<stdio.h>
int main()
{
int matrix1[3][3],matrix2[3][3],matrix3[3][3],a,b,c;
printf("Enter 9 Eelments for Matrix 1 : ");
for(a=0;a<3;a++)
{
for(b=0;b<3;b++)
{
scanf("%d",&matrix1[a][b]);
}
}
printf("Enter 9 Eelments for Matrix 2 : ");
for(a=0;a<3;a++)
{
for(b=0;b<3;b++)
{
scanf("%d",&matrix2[a][b]);
}
}
for(a=0;a<3;a++)
{
for(b=0;b<3;b++)
{
matrix3[a][b]=0;
for(c=0;c<3;c++)
{
matrix3[a][b]=matrix3[a][b]+(matrix1[a][c]*matrix2[c][b]);
}
}
}
printf("Matrix 1 : \n");
for(a=0;a<3;a++)
{
for(b=0;b<3;b++)
{
printf("%d ",matrix1[a][b]);
}
printf("\n");
}
printf("\nMatrix 2 : \n");
for(a=0;a<3;a++)
{
for(b=0;b<3;b++)
{
printf("%d ",matrix2[a][b]);
}
printf("\n");
}
printf("\nMultiplication of 2 Matrix (Matrix 3) : \n");
for(a=0;a<3;a++)
{
for(b=0;b<3;b++)
{
printf("%d ",matrix3[a][b]);
}
printf("\n");
}
return 0;
}
Output
Enter 9 Elements for Matrix 1 :
1 2 3
2 3 4
2 3 4
Enter 9 Elements for Matrix 2 :
1 2 3
2 3 3
3 4 2
Matrix 1 :
1 2 3
2 3 4
2 3 4
Matrix 2 :
1 2 3
2 3 3
3 4 2
Multiplication of 2 Matrix (Matrix 3) :
14 20 15
20 29 23
20 29 23