Matrix Addition in C++

Matrix is nothing but a set of numbers arranged in rows and columns. Adding 2 matrices is even simpler. Just add the corresponding entries of 2 matrices to get the corresponding element of result matrix. The 2 matrices should be of the same order, i.e., should have the same number of rows and columns. Here is the pictorial representation of 2*2 matrix added with another 2*2 matrix.

Matrix Addition
An example of matrix addition

To do the same task in C++, we have used 2-dimensional arrays mat1 and mat2. Here is the steps we’ve done in this program

  • Ask the user to enter the number of rows and columns. Number of rows and columns must be same for both matrices, so we ask only once.
  • Check if the entered value is not beyond our maximum array size or less than 1.
  • Read the 2 arrays from the user with nested for-loops.
  • Calculate the sum of to matrices with another nested for-loop.
  • Print the result matrix.
Here’s the program
 

 
You may optimize this program by doing some thing like:
  • Use pointers instead of matrices, thus allowing the user to enter matrix of any size at the same time saving memory.
  • You may perform addition while reading the second matrix, thus saving a few lines of code.
Matrix Subtraction
I know, it doesn’t need an explanation. Just changing a sign is enough for changing this program to perform matrix subtraction.
 

Leave a Reply

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