Advertisement

/* Write a program in C for multiplication of two Matrices. */
#include <stdio.h>

int main()
{
  int a[50][50],b[50][50],c[50][50];
  int i,j,k,r1,c1,r2,c2,sum=0;
  printf("Enter rows and columns of first matrix: ");
  scanf("%d %d",&r1,&c1);
  printf("Enter rows and columns of second matrix : ");
  scanf("%d %d",&r2,&c2);
  if(c1!=r2){
      printf("Mutiplication of Matrix is not possible.");
      printf("\nColumn of first matrix and row of second matrix must be same.");
  }
  else
  {
    printf("Enter elements in the first matrix :\n");
    for(i=0;i<r1;i++)
    {
        for(j=0;j<c1;j++)
        {
            printf("element - [%d][%d] : ",i,j);
            scanf("%d",&a[i][j]);
        }
    }
    printf("Enter elements in the second matrix :\n");
    for(i=0;i<r2;i++)
    {
        for(j=0;j<c2;j++)
        {
            printf("element - [%d][%d] : ",i,j);
            scanf("%d",&b[i][j]);
        }
    }
    printf("First matrix is: \n");
    for(i=0;i<r1;i++)
    {
        for(j=0;j<c1;j++)
        {
            printf("%d  ",a[i][j]);
        }
        printf("\n");
    }
    printf("Second matrix is: \n");
    for(i=0;i<r2;i++)
    {
        for(j=0;j<c2;j++)
        {
            printf("%d  ",b[i][j]);
        }
        printf("\n");
    }
    printf("\nThe resultant matrix is:\n");
    for(i=0;i<r1;i++)       //Multiplication of matrix
    {
        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("%d  ",c[i][j]);
        }
        printf("\n");
    }
  }
  return 0;
}

Output:
Enter rows and columns of first matrix: 2 3
Enter rows and columns of second matrix : 3 1
Enter elements in the first matrix :
element - [0][0] : 1
element - [0][1] : 2
element - [0][2] : 4
element - [1][0] : 2
element - [1][1] : 1
element - [1][2] : 5
Enter elements in the second matrix :
element - [0][0] : 3
element - [1][0] : 6
element - [2][0] : -2
First matrix is:
1  2  4
2  1  5
Second matrix is:
3
6
-2

The resultant matrix is:
7
2


Back

Post a Comment

0 Comments