Friday, January 2, 2015

C++ Program for adding two matrices

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
const int ROWS=3;
const int COLS=3;
int matrix1[ROWS][COLS];
int matrix2[ROWS][COLS];
int addmat[ROWS][COLS];
int r,c;
cout << "Enter the elements of matrix 1:\n";

for( r=0 ; r<ROWS ; r++ )
{
for( c=0 ; c<COLS ; c++ )
{
cout << "Enter the element "
<< (r+1) << "x" << (c+1)
<< ": ";
cin >> matrix1[r][c];
}
}
cout << "Enter the elements of matrix 2:\n";

for( r=0 ; r<ROWS ; r++ )
{
for( c=0 ; c<COLS ; c++ )
{
cout << "Enter the element "
<< (r+1) << "x" << (c+1)
<< ": ";
cin >> matrix2[r][c];
}
}
for( r=0 ; r<ROWS ; r++ )
{
for( c=0 ; c<COLS ; c++ )
{
addmat[r][c]=matrix1[r][c]+matrix2[r][c];
}
}
cout << "The added matrix is:\n";
for( r=0 ; r<ROWS ; r++ )
{
for( c=0 ; c<COLS ; c++ )
{
cout << setw(5)
<< addmat[r][c];
}
cout << endl;
}

cout << endl;


return 0;
}

No comments:

Post a Comment