Addition of two matrices in C++

In this tutorial, we will learn how to add two matrices using C++. Addition of two matrices in C++ is very much easy if you follow the below steps.

This program prints the Addition of the two matrices as an output.

Input for matrix

We should consider two matrices ‘A’ and ‘B’ of same number of rows and columns.

Let ‘A’ matrix having ‘r1’ rows and ‘c1’ columns and ‘B’ matrix having ‘r2’ rows and ‘c2’ columns.

int r1,c1;
cout<<"Enter the number of rows and columns of A matrix\n";
cin>>r1>>c1;
int r2,c2;
cout<<"Enter the number of rows and columns of B matrix\n";
cin>>r2>>c2;
int A[r1][c1],B[r2][c2];

In the above code, we have declared and read the variables for number of rows and columns of matrix ‘A’ and ‘B’.

How to read a matrix in C++

cout<<"Enter the values for the matrix A\n";
for(int i=0;i<r1;i++)
for(int j=0;j<c1;j++)
cin>>A[i][j];
cout<<"Enter the values for the matrix B\n";
for(int i=0;i<r2;i++)
for(int j=0;j<c2;j++)
cin>>B[i][j];

In the above code, we have read the values for the matrix ‘A’ and ‘B’.

The first for loop denotes the row of a matrix starting from index i=0.

The second for loop denotes the column of a matrix starting from index j=0.

input format:

Enter the number of rows and columns of A matrix
3 3
Enter the number of rows and columns of B matrix
3 3
Enter the values for the matrix A
1 3 5
2 4 6
1 3 2
Enter the values for the matrix B
4 5 6
3 4 2
5 1 5

C++ code to print Addition of two matrices

#include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<"Enter the number of rows and columns for matrix A\n";
int r1,c1;
cin>>r1>>c1;
cout<<"Enter the number of rows and columns for matrix B\n";
int r2,c2;
cin>>r2>>c2;
int A[r1][c1];
cout<<"Enter the values for matrix A\n";
for(int i=0;i<r1;i++)
for(int j=0;j<c1;j++)
cin>>A[i][j];
cout<<"Enter the values for matrix B\n";
int B[r2][c2];
for(int i=0;i<r2;i++)
for(int j=0;j<c2;j++)
cin>>B[i][j];
int C[r1][c1];
for(int i=0;i<r1;i++)
for(int j=0;j<c1;j++)
C[i][j]=A[i][j]+B[i][j];
cout<<"Addition of two matrices :\n";
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
cout<<C[i][j]<<" ";
cout<<endl;
}
return 0;
}

In the above code, for every value of i , j of matrix ‘A’ is subsequently adding with i , j values of matrix ‘B’ and is stored in the matrix ‘C’.

Therefore, we print the matrix ‘C’ which is the addition of matrix ‘A’ and ‘B’.

Output:

Addition of two matrices :

5 8 11

5 8 8

6 4 7

We hope this tutorial helped you to understand how to add the two matrices.