Friday, 16 March 2018

Matrix Multiplication in C

In C programming matrix is created by using 2D and 3D array but today we are working on matrix multiplication in C language.
Here the program to do Matrix Multiplication in C.

/* Pre-Processors */
#include <stdio.h>
#include<conio.h>
#define MAX 15 /*Length of MAX*/
int main()
{
  int m, n,i,j,k, sum = 0;
  int first[MAX][MAX], second[MAX][MAX], multiply[MAX][MAX];
  printf("Enter the number of rows and columns of first matrix\n");
  scanf("%d%d", &m, &n);
  printf("Enter the elements of first matrix\n");
 for (i = 0; i < m; i++)
    for (j = 0; j < n; j++)
      scanf("%d", &first[i][j]);
  printf("Enter the number of rows and columns of second matrix\n");
  scanf("%d%d", &m, &n);
printf("Enter the elements of second matrix\n");
 for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        scanf("%d",&second[i][j]);
  for (i = 0; i < m; i++) {
      for (j = 0; j < n; j++) {
        for (k = 0; k < n; k++) {
          sum = sum + first[i][k]*second[k][j];
        }
 multiply[i][j] = sum;
        sum = 0;
      }
    }

    printf("Product of entered matrices:-\n");
 for (i = 0; i < m; i++) {
      for (j = 0; j < n; j++)
        printf("%d\t", multiply[i][j]);
 printf("\n");
    }
 getch();
  return 0;
}

No comments:

Post a Comment