You are here

Matrix multiplication in C

Matrix multiplication in C language: 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.

Matrix multiplication in C language

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int m, n, p, q, c, d, k, sum = 0;
  6.   int first[10][10], second[10][10], multiply[10][10];
  7.  
  8.   printf("Enter number of rows and columns of first matrix\n");
  9.   scanf("%d%d", &m, &n);
  10.   printf("Enter elements of first matrix\n");
  11.  
  12.   for (c = 0; c < m; c++)
  13.     for (d = 0; d < n; d++)
  14.       scanf("%d", &first[c][d]);
  15.  
  16.   printf("Enter number of rows and columns of second matrix\n");
  17.   scanf("%d%d", &p, &q);
  18.  
  19.   if (n != p)
  20.     printf("The matrices can't be multiplied with each other.\n");
  21.   else
  22.   {
  23.     printf("Enter elements of second matrix\n");
  24.  
  25.     for (c = 0; c < p; c++)
  26.       for (d = 0; d < q; d++)
  27.         scanf("%d", &second[c][d]);
  28.  
  29.     for (c = 0; c < m; c++) {
  30.       for (d = 0; d < q; d++) {
  31.         for (k = 0; k < p; k++) {
  32.           sum = sum + first[c][k]*second[k][d];
  33.         }
  34.  
  35.         multiply[c][d] = sum;
  36.         sum = 0;
  37.       }
  38.     }
  39.  
  40.     printf("Product of the matrices:\n");
  41.  
  42.     for (c = 0; c < m; c++) {
  43.       for (d = 0; d < q; d++)
  44.         printf("%d\t", multiply[c][d]);
  45.  
  46.       printf("\n");
  47.     }
  48.   }
  49.  
  50.   return 0;
  51. }

An output of 3 X 3 matrix multiplication C program:

Matrix multiplication C program output

Download Matrix multiplication program.

Matrices are frequently used in programming and are used to represent graph data structure, in solving a system of linear equations and have many other applications. A lot of research is being done on how to multiply matrices using a minimum number of operations. You can also implement this program using pointers.