Multiplying two matrices in C

Last Updated On Thursday 11th Nov 2021

Multiplying two matrices is that the number of columns in the first matrix must be equal to the number of rows in the second matrix.

multiplication of two matrix in c

The nested loops that actually compute the matrix multiplication.

	for(i=0; i<2; i++)
{
    for(j=0; j<4; j++)
    {
        matR[i][j]=0;
        for(k=0; k<3; k++)
        {
            matR[i][j]=matR[i][j]+matA[i][k]*matB[k][j];
        }
    }
}
	
  • Variable i represents the row of the resultant matrix.
  • Variable j represents the column of the resultant matrix.
  • Variable k represents the common factor.
	#include <stdio.h>
int main ()
{
    int matA[2][3], matB[3][4], matR[2][4];
    int i, j, k;
    printf ("Enter elements of the first matrix of order 2 x 3 \n");
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 3; j++)
        {
            scanf ("%d", &matA[i][j]);
        }
    }
    printf ("Enter elements of the second matrix of order 3 x 4 \n");
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 4; j++)
        {
            scanf ("%d", &matB[i][j]);
        }
    }
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 4; j++)
        {
            matR[i][j] = 0;
            for (k = 0; k < 3; k++)
            {
                matR[i][j] = matR[i][j] + matA[i][k] * matB[k][j];
            }
        }
    }
    printf ("\nFirst Matrix is \n");
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 3; j++)
        {
            printf ("%d\t", matA[i][j]);
        }
        printf ("\n");
    }
    printf ("\nSecond Matrix is \n");
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 4; j++)
        {
            printf ("%d\t", matB[i][j]);
        }
        printf ("\n");
    }
    printf ("\nMatrix multiplication is \n");
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 4; j++)
        {
            printf ("%d\t", matR[i][j]);
        }
        printf ("\n");
    }
    return 0;
}
	
	Enter elements of the first matrix of order 2 x 3 
Enter elements of the second matrix of order 3 x 4 

First Matrix is 
1   2   3   
4   5   6   

Second Matrix is 
7   8   9   10  
11  12  13  14  
15  16  17  18  

Matrix multiplication is 
74  80  86  92  
173 188 203 218