Summary: In this programming example, we will learn how to multiply two matrices in C++.


Condition for Matrix Multiplication

Two matrices A and B can be multiplied only if the number of columns in A is equal to the number of rows in B.

Matrix multiplication in C++

Also, the order of the resultant matrix is as follows:

  • row = number of rows in the first matrix.
  • columns = number of columns in the second matrix.

So before multiplying, first we verify the order of the given matrix and then define the order for the resulting matrix accordingly.

Algorithm to Multiply Two Matrix in C++

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

Basically, we have to nest 3 ‘for’ loops in order to multiply and store the multiplication result into the resultant matrix.

Here is the C++ example that multiply two given matrices:


Resultant Matrix
6 11
3 6

In this tutorial, we learned to multiply matrices in the C++ programming language.

Leave a Reply

fourteen + 15 =