Matrix Multiplication in C++

In previous post, i’ve explained how to write a program to perform matrix addition. Now we’ll look how to perform matrix multiplication in C++. Before continuing, this picture will explain you how multiply 2 matrices manually.

Matrix Multiplication
An example of matrix multiplication

 

I hope no more explanation is needed for this. To perform matrix multiplication, number of columns of first matrix should be equal to number of rows of second matrix. 

Steps:

  • Read number of rows and columns of first matrix
  • Read first matrix
  • Read number of rows and columns of second matrix
  • Check whether no.of columns in first matrix = no.of rows in second matrix
  • Read second matrix
  • Multiply the matrices
  • Print the result
Easy as that! Now see these steps converted into C++ code:

 
Let me explain again. We operate each rows of first matrix with each columns of matrix 2. By saying ‘operate’, i mean multiplying corresponding elements and adding up all together as in picture above. Hence we need 3 for-loops in nested form to multiply 2 matrices. The outermost for-loop loops through each rows of matrix 1. Second for-loop loops through each column of second matrix. We do the actual calculation in the innermost for-loop which multiplies corresponding elements of currently selected row and column and add up to get one of the element in result matrix. Before starting innermost loop we set the current element of result matrix to zero, to prevent garbage value from being added up.
 
You have a lot more to do to make it a perfect one, which i have skipped for keeping it simple:
  • Check whether entered size of matrix is below the maximum of array size.
  • You may ask for the user to enter size of second matrix before entering matrix 1, thus telling the user whether it cannot be multiplied before entering the whole matrix.
  • Use pointers instead of matrices, thus allowing the user to enter matrix of any size at the same time saving memory.
  • You may print the result while calculating, thus saving a few lines of code.

Leave a Reply

Your email address will not be published. Required fields are marked *