Program to add two Matrices
Addition of two matrices is the simplest operation one can perform on matrices. It just requires the basic knowledge of addition of numbers. One must also keep in mind that only the like matrices can be added together. By the term “LIKE” I mean that only the matrices with same number of rows and columns.
Follow on with the examples given below to first understand the addition of two matrices:
Consider the following two matrices which are being added:
Consider the following two matrices which are being added:
To add them just add the pairs of entries, and then simplify for the final answer:
Running Program Code:
#include<iostream.h> #include<process.h> #include<iomanip.h> #include<conio.h> const int max=10; void line(int); void main() { clrscr(); char ch; int A[max][max],B[max][max],C[max][max],m,n,i,j; cout<<"\n\n\t\tTHIS WILL ADD TWO MATRICES\t\t\n"<<endl; cout<<"\n\nFor adding two matrices, both should be square matrix"; cout<<" and of equal dimension\n"<<endl; do { cout<<"\nEnter dimension of the square matrix : "; cin>>m; if(m>max) cout<<"\n\nEnter dimension less than "<<max; } while(m>max); cout<<endl; cout<<"\n\nEnter the FIRST matix (row wise) : "<<endl; for(i=0; i<m; ++i) { for(j=0; j<m; ++j) { cout<<"\nElement at position ["<<i<<"]["<<j<<"] : "; cin>>A[i][j]; } } cout<<"\n\nThe FIRST matrix is : \n\n"; for(i=0; i<m; ++i) { cout<<"\n\t\t"; for(j=0; j<m; ++j) { cout<<setw(5)<<A[i][j]; } cout<<"\n\n"; } cout<<endl; cout<<"\n\nEnter the SECOND matix (row wise) : "<<endl; for(i=0; i<m; ++i) { for(j=0; j<m; ++j) { cout<<"\nElement at position ["<<i<<"]["<<j<<"] : "; cin>>B[i][j]; } } cout<<"\n\nThe SECOND matrix is : \n\n"; for(i=0; i<m; ++i) { cout<<"\n\t\t"; for(j=0; j<m; ++j) { cout<<setw(5)<<B[i][j]; } cout<<"\n\n"; } cout<<endl; for(i=0; i<m; ++i) for(j=0; j<m; ++j) C[i][j]=A[i][j]+B[i][j]; cout<<"\n\nThe added elenments are : \n"; for(i=0; i<m; ++i) { for(j=0; j<m; ++j) { cout<<"\n\nElement at position ["<<i<<"]["<<j<<"] : "; cout<<C[i][j]; } } cout<<"\n\n\nThe sum of the two matrices is : \n\n"; for(i=0; i<m; ++i) { cout<<"\n\t\t"; for(j=0; j<m; ++j) { cout<<setw(5)<<C[i][j]; } cout<<"\n\n"; } getch(); }

Comments
Post a Comment