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.

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
#include<iostream> using namespace std; #define MAXSIZE 10 int main() { int mat1[MAXSIZE][MAXSIZE], mat2[MAXSIZE][MAXSIZE], mat3[MAXSIZE][MAXSIZE], row, col, i, j; /* Read the size of matrices */ cout<<"Enter the number of rows: "; cin>>row; cout<<"Enter the number of cols: "; cin>>col; /* Check whether entered size doesnt exceed the limit */ if(row<1 || row>MAXSIZE || col<1 || col>MAXSIZE) { cout<<"Size limit exceeded!"; return 0; } /* Read the first matrix */ cout<<"Enter the elements in matrix 1:n"; for(i=0; i<row; ++i) { for(j=0; j<col; ++j) { cin>>mat1[i][j]; } } /* Read the second matrix */ cout<<"Enter the elements in matrix 2:n"; for(i=0; i<row; ++i) { for(j=0; j<col; ++j) { cin>>mat2[i][j]; } } /* Calculate the sum */ for(i=0; i<row; ++i) { for(j=0; j<col; ++j) { mat3[i][j] = mat1[i][j] + mat2[i][j]; } } /* Print the result */ cout<<"nSum of 2 matrices:"; for(i=0; i<row; ++i) { cout<<"n"; for(j=0; j<col; ++j) { cout<<mat3[i][j]<<" "; } } return 0; } |

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.

1 2 3 4 5 6 7 |
for(i=0; i<row; ++i) { for(j=0; j<col; ++j) { mat3[i][j] = mat1[i][j] - mat2[i][j]; } } |