Matrix Multiplication Program in C- Programmer's Mind


Matrix Multiplication:

In programming Matrices will be stored in Two Dimensional Arrays.
 process of multiplication in general

Precondition:

     Number of columns in First matrix should be equal to Number of rows in the second matrix.

In below Example Two matrices of order 2*2.Here Matrix Multiplication is possible as the Precondition is satisfied.Order of resultant matrix also 2*2 (Rows in first Matrix * Columns in second Matrix)



Process of Matrix Multiplication




















Program For Matrix Multiplication

#include<stdio.h>
void main()
 {
   int r1,c1,r2,c2,i,j,k,a[5][5],b[5][5],c[5][5];
   //Reading First Matrix
   printf("Enter Number of rows and columns of First Matrix:\n");
   scanf("%d %d",&r1,&c1);
   for(i=0;i<r1;i++)
   {
    for(j=0;j<c1;j++)
    {
     printf("Enter a[%d][%d]",i,j);
     scanf("%d",&a[i][j]);
    }
   }
   //Reading Second Matrix
   printf("Enter Number of rows and columns of Second Matrix:\n");
   scanf("%d %d",&r2,&c2);
  for(i=0;i<r2;i++)
   {
    for(j=0;j<c2;j++)
    {
     printf("Enter a[%d][%d]",i,j);
     scanf("%d",&b[i][j]);
    }
   }
   // Checking precondition
   if(c1==r2)
    {
     for(i=0;i<r1;i++)
      {
       for(j=0;j<c2;j++)
 {
  c[i][j]=0;
  for(k=0;k<c1;k++)
   {
    c[i][j]+=a[i][k]*b[k][j];
   }
 }
      }
     printf("Resultant Matrix:\n");
     for(i=0;i<r1;i++)
     {
      for(j=0;j<c2;j++)
      {
       printf("%d  ",c[i][j]);
      }
      printf("\n");
     }
    }
   else
    {
     printf("Multiplication not possible");
    }
 }


Output of Matrix Multiplication Program:


Output of Matrix Multiplication Program
Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment