Sunday, 3 February 2013

Write a c program to multiply two matrix

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],n1,n2,m1,m2,i,j,k;
clrscr();
printf("Enter Matrix Length A (M1 x N1):");
scanf("%d%d",&m1,&n1);
printf("Enter Matrix A:");
for(i=0; i<m1; i++){
   for(j=0; j<n1; j++){
    scanf("%d"<&a[i][j]);
   }
}
printf("Enter Matrix Length B (M2 x N2):");
scanf("%d%d",&m2,&n2);
printf("Enter Matrix B:");
for(i=0; i<m2; i++){
   for(j=0; j<n2; j++){
    scanf("%d"<&a[i][j]);
   }
}

if(n1!=m2){
  printf("Multiplication not valid!");
  getch();
  exit (0);
}

for(i=0; i<m2; i++){
  for(j=0; j<n1; j++){
  c[i][j]=0;
    for(k=0; k<m2; k++){
    c[i][j]=c[i][j]+a[i][k]*b[k][i];
    }
  }
}

printf("The Result is:");
for(i=0; i<m2; i++){
  printf("\n");
  for(j=0; j<n1; j++){
  printf("%d\t",c[i][j]);
  }
}
getch();
}

Output:

Enter Matrix Length A (M1 x N1):2 3
Enter Matrix A:
2 3
2 1
0 1

Enter Matrix Length B (M2 x N2):2 2
Enter Matrix B:
2 1
1 2

Multiplication not Valid!

Enter Matrix Length A (M1 x N1):2 2
Enter Matrix A:
2 3
2 1

Enter Matrix Length B (M2 x N2):2 2
Enter Matrix B:
3 2
2 1

The Result is:
12   7
8    5

Thanks for wathing...
Comment it...

No comments:

Post a Comment