Given two matrices of the same dimensions, the task is to find their sum by adding the corresponding elements of both matrices. Matrix addition is performed only when both matrices have the same number of rows and columns.
- Each element in the resultant matrix is the sum of the corresponding elements of the two input matrices.
- The matrices can be square or rectangular, as long as their dimensions are the same.
Example:
Input:
A = {{1, 2},
{3, 4}}
B = {{5, 6},
{7, 8}}Output:
{{6, 8},
{10, 12}}Explanation:
The corresponding elements of the two matrices are added:
C[0][0] = 1 + 5 = 6
C[0][1] = 2 + 6 = 8
C[1][0] = 3 + 7 = 10
C[1][1] = 4 + 8 = 12

Approach
To add two matrices, traverse both matrices row by row and column by column. For every position (i, j), add the elements at the same position in the two matrices and store the result in a third matrix.
Steps:
- Initialize two matrices A and B with the same dimensions.
- Create a resultant matrix C of the same dimensions.
- Traverse every row and column of the matrices.
- Add A[i][j] and B[i][j] and store the result in C[i][j].
- Print the resultant matrix.
#include <iostream>
using namespace std;
#define N 4
// Function to add two matrices
void add(int A[][N], int B[][N], int C[][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}
// Driver code
int main()
{
int A[N][N] = {
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}
};
int B[N][N] = {
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}
};
// Resultant matrix
int C[N][N];
add(A, B, C);
cout << "Result matrix is:\n";
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
Result matrix is: 2 2 2 2 4 4 4 4 6 6 6 6 8 8 8 8
Code Explanation
- add() traverses both matrices using nested loops.
- It adds corresponding elements and stores the result in matrix C.
- main() initializes the matrices, calls add(), and prints the resultant matrix.