C++ Program to add two matrices

Simple C++ Program to add two matrix into third matrix. To add two matrix , we add corresponding position elements of both matrix.

/* C++ Program to add two matrices */
#include<iostream>
using namespace std;
int main()
{
 int m1[3][3], m2[3][3], m3[3][3];
 
 cout<<"Enter first matrix elements: "<<endl;
 for(int i=0;i<3;i++)
 {
  for(int j=0;j<3;j++)
  {
   cin>>m1[i][j];
  }
 }
 
 cout<<"Enter second matrix elements: "<<endl;
 for(int i=0;i<3;i++)
 {
  for(int j=0;j<3;j++)
  {
   cin>>m2[i][j];
  }
 }
 
    /* add m1 and m2 matrices into m3 */ 
    for(int i=0;i<3;i++)
    {
     for(int j=0;j<3;j++)
     {
      m3[i][j]=m1[i][j]+m2[i][j];
  }
 }
 
 /* print m3 matrix */
 cout<<"Addition of two matrices: "<<endl;
 for(int i=0;i<3;i++)
    {
     for(int j=0;j<3;j++)
     {
      cout<<m3[i][j]<<"  ";
  }
  cout<<endl;
 }
 
 return 0;
}

Another C++ program to add two matrices without third matrix

/* C++ Program to add two matrix */
#include<iostream>
using namespace std;
int main()
{
 int m1[3][3], m2[3][3];
 
 cout<<"Enter first matric elements: "<<endl;
 for(int i=0;i<3;i++)
 {
  for(int j=0;j<3;j++)
  {
   cin>>m1[i][j];
  }
 }
 
 cout<<"Enter second matrix elements: "<<endl;
 for(int i=0;i<3;i++)
 {
  for(int j=0;j<3;j++)
  {
   cin>>m2[i][j];
  }
 }
 
    /* add m1 and m2 matrices into m1 */ 
    for(int i=0;i<3;i++)
    {
     for(int j=0;j<3;j++)
     {
      m1[i][j]=m1[i][j]+m2[i][j];
  }
 }
 
 /* print m3 matrix */
 cout<<"Addition of two matrixs: "<<endl;
 for(int i=0;i<3;i++)
    {
     for(int j=0;j<3;j++)
     {
      cout<<m1[i][j]<<"  ";
  }
  cout<<endl;
 }
 
 return 0;
}



Popular posts from this blog