C++ Program to Add Two Matrices

Here you will get a C++ program to find the addition of two matrices. We can add two matrices only if they have similar dimensions.

For example:

Matrix A:

3 7
2 5

Matrix B:

5 6
1 4

The addition of A and B is:

8 13
3 9

Let us see the code for matrix addition in C++.

#include<iostream>

using namespace std;
 
int main()
{
	int A[10][10],B[10][10],c[10][10];
	int i,j,m,n,p,q;
	
	cout<<"Enter no. of rows and columns of matrix A:";
	cin>>m>>n;
	cout<<"\nEnter no. of rows and columns of matrix B:";
	cin>>p>>q;
	
	cout<<"\nEnter matrix A row wise:";
	
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
			cin>>A[i][j];
	}
	
	cout<<"\nMatrix A:\n";
	
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		cout<<A[i][j]<<" ";
		cout<<"\n";
	}
	
	cout<<"\nEnter Matrix B row wise:";
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		cin>>B[i][j];
	}
	
	cout<<"\n\nMatrix B:\n";
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		cout<<B[i][j]<<" ";
		cout<<"\n";
	}
	
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		c[i][j]=A[i][j]+B[i][j];
	}
	
	cout<<"\nSum of Matrices A and B:\n";
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		cout<<c[i][j]<<" ";
		cout<<"\n";
	}
	
	return 0;
}

Output:

Enter no. of rows and columns of matrix A:2
2
Enter no. of rows and columns of matrix B:2
2
Enter matrix A row wise:2 2
3 3
Matrix A:
2 2
3 3
Enter Matrix B row wise:2 2
3 3
Matrix B:
2 2
3 3
Sum of Matrices A and B:
4 4
6 6

Leave a Comment

Your email address will not be published. Required fields are marked *