C++ program to add two matrices has been shown here. Two matrices $[A]_{m \times n}$ and $[B]_{p \times q}$ are considered for addition if the number of rows and columns are same in both of the matrices i.e. $m = p$ and $n = q$.

Algorithm, pseudocode and time complexity of the program have also been shown.

#### Page content(s):

1. Program & Output: Iterative approach

1. Algorithm

2. Pseudocode

3. Time Complexity

## 1. C++ Program for matrix addition

Code has been copied
/***************************************
alphabetacoder.com
***************************************/
#include <iostream>

using namespace std;

int main(){
// declare variables
int m,n,p,q,i,j;
int A[10][10]={0},B[10][10]={0};

//take input of the order of first matrix
cout<<"Enter the number of row and column of first matrix=";
cin>>m;
cin>>n;

//take input of the first matrix
cout<<"Enter the first matrix of order "<<m<<" x "<<n<<" =\n";
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>A[i][j];

//take input of the order of second matrix
cout<<"Enter the number of row and column of second matrix=";
cin>>p;
cin>>q;

//take input of the second matrix
cout<<"Enter the second matrix of order "<<p<<" x "<<q<<" =\n";
for(i=0;i<p;i++)
for(j=0;j<q;j++)
cin>>B[i][j];

// check if order of matrices are same
// if not then addition of two matrices is not possible
if(m!=p||n!=q)
cout<<"\nMatrices are of different order,hence addition is not possible";
else{
// and print the resultant matrix
for(i=0;i<m;i++){
for(j=0;j<n;j++)
cout<<A[i][j]+B[i][j];
cout<<"\n";
}
}
return 0;
}


Output

#### Case 1:

Enter the number of row and column of first matrix=3 3

Enter the first matrix of order 3 x 3=

3 5 7

4 5 9

0 1 1

Enter the number of row and column of second matrix=2 3

Enter the second matrix of order 2 x 3=

9 4 5

3 7 8

1 2 3

12 9 12

7 12 17

1 3 4

#### Case 2:

Enter the number of row and column of first matrix=3 3

Enter the first matrix of order 3 x 3=

3 5 7

4 5 9

0 1 1

Enter the number of row and column of second matrix=2 3

Enter the second matrix of order 2 x 3=

9 4 5

3 7 8

Matrices are of different order,hence addition is not possible