0
0
CppProgramBeginner · 2 min read

C++ Program to Add Two Matrices with Output

To add two matrices in C++, use nested loops to sum corresponding elements and store them in a result matrix, like result[i][j] = matrix1[i][j] + matrix2[i][j]; inside two for loops iterating over rows and columns.
📋

Examples

InputMatrix1 = [[1, 2], [3, 4]], Matrix2 = [[5, 6], [7, 8]]
Output[[6, 8], [10, 12]]
InputMatrix1 = [[0, 0], [0, 0]], Matrix2 = [[0, 0], [0, 0]]
Output[[0, 0], [0, 0]]
InputMatrix1 = [[-1, 2], [3, -4]], Matrix2 = [[4, -2], [-3, 4]]
Output[[3, 0], [0, 0]]
🧠

How to Think About It

To add two matrices, think of them as grids of numbers. You add the number in the first row and first column of the first matrix to the number in the first row and first column of the second matrix, then do the same for every position. This means you use two loops: one for rows and one for columns, and add matching elements.
📐

Algorithm

1
Get the number of rows and columns for the matrices.
2
Create a result matrix of the same size.
3
For each row index from 0 to number of rows - 1:
4
For each column index from 0 to number of columns - 1:
5
Add the elements from both matrices at this position and store in the result matrix.
6
Print the result matrix.
💻

Code

cpp
#include <iostream>
using namespace std;

int main() {
    int rows = 2, cols = 2;
    int matrix1[2][2] = {{1, 2}, {3, 4}};
    int matrix2[2][2] = {{5, 6}, {7, 8}};
    int result[2][2];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }

    cout << "Resultant Matrix:\n";
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << result[i][j] << " ";
        }
        cout << "\n";
    }
    return 0;
}
Output
Resultant Matrix: 6 8 10 12
🔍

Dry Run

Let's trace adding matrices [[1, 2], [3, 4]] and [[5, 6], [7, 8]] through the code.

1

Initialize matrices and result

matrix1 = [[1, 2], [3, 4]], matrix2 = [[5, 6], [7, 8]], result = [[?, ?], [?, ?]]

2

Add element at row 0, col 0

result[0][0] = 1 + 5 = 6

3

Add element at row 0, col 1

result[0][1] = 2 + 6 = 8

4

Add element at row 1, col 0

result[1][0] = 3 + 7 = 10

5

Add element at row 1, col 1

result[1][1] = 4 + 8 = 12

6

Print result matrix

Resultant Matrix: 6 8 10 12

Positionmatrix1[i][j]matrix2[i][j]result[i][j]
[0][0]156
[0][1]268
[1][0]3710
[1][1]4812
💡

Why This Works

Step 1: Matrix elements correspond by position

Each element in the first matrix has a matching element in the second matrix at the same row and column, so we add those pairs.

Step 2: Use nested loops to access all elements

Two loops let us visit every row and column index to perform addition on all elements.

Step 3: Store sums in a new matrix

We keep the sums in a separate matrix so the original matrices stay unchanged and we can print the result.

🔄

Alternative Approaches

Using vectors instead of arrays
cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<vector<int>> matrix1 = {{1, 2}, {3, 4}};
    vector<vector<int>> matrix2 = {{5, 6}, {7, 8}};
    vector<vector<int>> result(2, vector<int>(2));

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }

    cout << "Resultant Matrix:\n";
    for (auto &row : result) {
        for (auto &val : row) cout << val << " ";
        cout << "\n";
    }
    return 0;
}
Vectors provide dynamic sizing and safer memory management but add slight overhead compared to arrays.
Adding matrices with user input
cpp
#include <iostream>
using namespace std;

int main() {
    int rows, cols;
    cout << "Enter rows and columns: ";
    cin >> rows >> cols;
    int matrix1[10][10], matrix2[10][10], result[10][10];

    cout << "Enter first matrix:\n";
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            cin >> matrix1[i][j];

    cout << "Enter second matrix:\n";
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            cin >> matrix2[i][j];

    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            result[i][j] = matrix1[i][j] + matrix2[i][j];

    cout << "Resultant Matrix:\n";
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            cout << result[i][j] << " ";
        cout << "\n";
    }
    return 0;
}
This approach allows adding matrices of any size up to 10x10, but requires user input and fixed max size.

Complexity: O(rows * cols) time, O(rows * cols) space

Time Complexity

The program uses two nested loops to visit each element once, so the time grows with the total number of elements.

Space Complexity

A new matrix is created to store the sum, so space grows with the size of the matrices.

Which Approach is Fastest?

Using arrays or vectors both have similar time complexity; vectors add flexibility but may have slight overhead.

ApproachTimeSpaceBest For
Static arraysO(rows * cols)O(rows * cols)Fixed size, simple cases
VectorsO(rows * cols)O(rows * cols)Dynamic size, safer memory
User input with arraysO(rows * cols)O(rows * cols)Flexible size with input
💡
Always check that both matrices have the same dimensions before adding them to avoid errors.
⚠️
Beginners often forget to use nested loops and try to add matrices element-wise without looping through rows and columns.