C++ program for addition of two matrices - coderforcoders

Search

Wednesday, 13 March 2019

C++ program for addition of two matrices

Addition of two matrix in c++

Theory:

The addition of two matrix is a simple c++ program written using concepts like class and object. A class matrix is used to declare the data members mat1, mat2 and the result matrix in 2D array format.
This class also contains variables such as i, j, m, n which is used in looping statements. Here we are using one member function addmat(), which adds the two matrices and displays the result.

Logic:

The addition of two matrix requires two looping statements nested one inside the another to fetch the values of rows and columns. The add statement should be written inside the second looping statement as given below,
 
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
result[i][j]=mat1[i][j]+mat2[i][j];
}
}


program: 

C++ program for addition of two matrices.

#include<iostream>
using namespace std;
class matrix{
public:
int mat1[100][100],mat2[100][100],result[100][100];
int i,j,m,n;
void addmat()
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
result[i][j]=mat1[i][j]+mat2[i][j];
}
}
cout<<" The resultant matrix is \n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<result[i][j]<<"\t";
}
cout<<endl;
}
}
};
int main()
{
matrix obj1;
int i,j;
cout<<"Please enter the size of matrices (m*n)\n";
cin>>obj1.m>>obj1.n;
cout<<"Please enter elements of first matrix\n";
for(i=0;i<obj1.m;i++)
for(j=0;j<obj1.n;j++)
cin>>obj1.mat1[i][j];
cout<<"Please enter elements of Second matrix\n";
for(i=0;i<obj1.m;i++)
for(j=0;j<obj1.n;j++)
cin>>obj1.mat2[i][j];
obj1.addmat();
cout<<endl;
}


Output 1:
Please enter the size of matrices (m*n)
3 3
Please enter elements of first matrix
1 2 3
4 5 6
7 8 9
Please enter elements of first matrix
9 8 7
6 5 4
3 2 1
The resultant matrix is
10 10 10
10 10 10
10 10 10


No comments:

Post a Comment