Matrix Addition in C++
Here you will learn and get the example code of Matrix Addition in C++ programming.
How to do matrix addition?
First we will get size of matrix, Input elements of matrix 1 and matrix 2, calculate the addition of matrix, and print the matrix 3 as result. This program will be a good example of 2d array.
Matrix addition is only possible if two matrix have same dimensions.
Example code of Matrix Addition in C++
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 | #include<iostream> using namespace std; main() { int x[5][5],y[5][5],z[5][5],i,j; int r,c; //input size of matrix cout<<"\nEnter No of Rows & Columns (max : 5,5) :"; cin>>r>>c; //input matrix 1 elements cout<<"\nEnter Elements for 1st Matrix : "; for(i=0;i<r;i++) { for(j=0;j<c;j++) cin>>x[i][j]; } //input matrix 2 elements cout<<"\nEnter Elements for 2nd Matrix : "; for(i=0;i<r;i++) { for(j=0;j<c;j++) cin>>y[i][j]; } //print matrix 1 elements cout<<"\nThe Elements In 1st Matrix : \n\n"; for(i=0;i<r;i++) { for(j=0;j<c;j++) cout<<x[i][j]<<" "; cout<<"\n"; } //print matrix 2 elements cout<<"\nThe Elements In 2nd Matrix : \n\n"; for(i=0;i<r;i++) { for(j=0;j<c;j++) cout<<y[i][j]<<" "; printf("\n"); } // Addition of Matrix for(i=0;i<r;i++) { for(j=0;j<c;j++) z[i][j]=x[i][j]+y[i][j]; } //print matrix After addition cout<<"\nThe Elements After Addition : \n\n"; for(i=0;i<r;i++) { for(j=0;j<c;j++) cout<<z[i][j]<<" "; cout<<"\n"; } return 0; } |
Output
Enter No of Rows & Columns (max : 5,5) :2
2
Enter Elements for 1st Matrix : 1
2
3
4
Enter Elements for 2nd Matrix : 1
2
3
4
The Elements In 1st Matrix :
1 2
3 4
The Elements In 2nd Matrix :
1 2
3 4
The Elements After Addition :
2 4
6 8
Other Similar Programs
Find Highest and Lowest Element of a Matrix in C++
Check out our other C++ programming Examples