Dark mode logo
Last Updated:

Matrix multiplication in C

Algorithm

Input: Input rows and column of the first and second matrices, elements of the matrices
output: Displays the multiplication of element of the matrices

  1. Start
  2. Input the number of row and column of 1st matrix and store it in m1, n1
  3. Input the number of row and column of 2nd matrix and store it in m2, n2
  4. if n1 != m2
    4.1 Print "Matrix multiplication not possible"
  5. else
    5.1 Input the elements of matrix 1 and matrix 2 say a [m1] [n1] and b [m2] [n2]
    5.2 Print "The multiplication of matrix 1 and 2 is "
    5.3 for i = 0 to m1
      5.3.1 for j = 0 to n2
        5.3.1.1 c [ i ] [ j ] = 0
        5.3.1.2 for k = 0 to n1
          5.3.1.2.1 c [ i ] [ j ] = c [ i ] [ j ] + a [ i ] [ k ] * b [ k ] [ j ]
  6. print the matrix c
  7. Stop

C Program

# include <stdio.h>
int main()

{
//Enter the rows and columns and elements of the first and second array
int n1,m1,n2,m2;
printf("Enter the number of rows of the first matrix: ");
scanf("%d", &m1);
printf("Enter the number of column of the first matrix: ");
scanf("%d", &n1);
printf("Enter the number of rows of the second matrix: ");
scanf("%d", &m2);
printf("Enter the number of column of the second matrix: ");
scanf("%d", &n2);
int a[m1][n1], b[m2][n2], c[m1][n2];

if (n1 != m2){
   printf("Matrix multiplication is not possible");
}
else {
//Input the first matrix
printf("Enter the elements of the first matrix: \n");
for (int i = 0; i < n1; i++){
   for (int j = 0; j < m1; j++)
   scanf("%d", &a[i][j]);
}

//Input the second matrix
printf("Enter the elements of the second matrix: \n");
for (int i = 0; i < n2; i++){
   for (int j = 0; j < m2; j++)
    scanf("%d", &b[i][j]);
}

//Matrix multiplication and storing
printf("The matrix multiplication is \n");
for (int i = 0; i < m1; i++){
    for (int j = 0; j< n2; j++){
       c [i][j] = 0;
       for (int k = 0; k <n1; k++){
       c [i] [j] = c [i] [j] + ( a[j] [k] * b [k] [j] );
        }
    }
}

//Print the matrix c
for (int i = 0; i < m1; i++){
        printf("\n");
    for (int j = 0; j < n2; j++){
        printf ("%d\t", c [i][j]);
   }}
}
return 0;
}


Note: This Program was created using visual studio code. The Program file can be downloaded by clicking here

Output

Enter the number of rows of the first matrix: 2
Enter the number of columns of the first matrix: 2
Enter the number of rows of  the second matrix: 2
Enter the number of columns of the second matrix: 2
Enter the elements of the first matrix:
1
2
3
4
Enter the elements of the second matrix:
1
2
3
4
The matrix multiplication is

7       22
7       22

Comments