Summary: In this programming example, we will learn how to multiply two matrices in C using nested for loops.

A matrix in C programming language can be represented using a 2D array, where the order of the matrix is the dimensions of the 2D array.

Since matrices can be represented in C, they can be also be multiplied easily using the C programming language.

Condition for Matrix Multiplication

Two matrices can only be multiplied if the number of columns of the first matrix is equal to the number of rows of the second matrix.

Matrix multiplication condition

If the multiplication is valid, the order of the resultant matrix would be (row of the first matrix * column of the second matrix).

Therefore, in order to multiply two matrices, we first have to verify their order.

Matrix Multiplication

To multiply two matrices:

  • Declare a 2D array to hold resultant matrix values.
  • Loop (I) from 0 to row order of the first matrix.
    • Nest (J) another loop from 0 to the column order of the second matrix.
      • Nest another loop (K) from 0 to row order of the second matrix.
        • Sum (matrix1[I][K] * matrix2[K][J])
      • Store the final sum into the resultant matrix as res[I][J] = sum.
    • End (J) loop.
  • End (I) loop.

Here is an example of multiplication of two matrices in C:

Output:

Matrix multiplication in C

In this tutorial, we learned to multiply two matrices in C. If you have any suggestiong or doubts then comment below.

Leave a Reply