2 Aug 2019

  • August 02, 2019
  • Amitraj




Matrix multiplication in C

C program to multiply two matrices (two-dimensional arrays) which will be entered by a user. The user will enter the order of a matrix and then its elements and similarly inputs the second matrix. If the orders of the matrices are such that they can't be multiplied by each other, then an error message is displayed. You may have studied the method to multiply matrices in Mathematics.

We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input from the user for row number, column number, first matrix elements and second matrix elements. Then we are performing multiplication on the matrices entered by the user.

In matrix multiplication first matrix one row element is multiplied by second matrix all column elements.




/*  C Program to multiply two matrices of order m*n */     By Amit raj purohit
  http://codevidyalay.blogspot.com

#include<stdio.h>
int main()
{
int a[9][9],b[9][9],c[9][9],i,j,k,m,n,p,q;
printf("Enter Matrix A order:");
scanf("%d%d",&m,&n);

printf("Enter Matrix B order:");
scanf("%d%d",&p,&q);
if(n!=p)
{

printf("Matrix multiplication is not possible!!!");

}
else
{
printf("Enter %d elements of matrix A:",m*n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

printf("Enter %d elements of matrix B:",p*q);
for(i=0;i<p;i++)
for(j=0;j<q;j++)

scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)

c[i][j]+=a[i][k]*b[k][j];
}
}
printf("Result C is :\n");
for(i=0;i<m;i++)

{
for(j=0;j<q;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
}
return 0;
}


INPUT/OUTPUT:
Enter Matrix A Order:2 2
Enter Matrix B order:2 2
Enter 4 elements of matrix A:
1 2
3 4
Enter 4 elements of matrix B:
1 0
0 1
Result C is :
1 2
3 4






Translate

Popular Posts