# C++ Program to Add Two Matrices

12/06/2024

Adding two matrices involves summing the corresponding elements of the matrices.

Problem Statement

Given two matrices of the same dimensions, add them element-wise and store the result in a new matrix.

Approach

1. Matrix Validation: Ensure both matrices have the same dimensions.
2. Element-wise Addition: Loop through each element of the matrices, add corresponding elements, and store the result in a new matrix.

Example

Given two 3×3 matrices:

Matrix A:

1 2 3

4 5 6

7 8 9

Matrix B:

9 8 7

6 5 4

3 2 1

10 10 10

10 10 10

10 10 10

C++ Code Implementation

#include <iostream>

#include <vector>

using namespace std;

// Function to add two matrices

vector<vector<int>> addMatrices(const vector<vector<int>>& matrixA, const vector<vector<int>>& matrixB) {

int rows = matrixA.size();

int cols = matrixA[0].size();

vector<vector<int>> result(rows, vector<int>(cols, 0));

for (int i = 0; i < rows; ++i) {

for (int j = 0; j < cols; ++j) {

result[i][j] = matrixA[i][j] + matrixB[i][j];

}

}

return result;

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

for (const auto& row : matrix) {

for (const auto& elem : row) {

cout << elem << ” “;

}

cout << endl;

}

}

int main() {

// Initializing two 3×3 matrices

vector<vector<int>> matrixA = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

vector<vector<int>> matrixB = {

{9, 8, 7},

{6, 5, 4},

{3, 2, 1}

};

cout << “Matrix A:” << endl;

printMatrix(matrixA);

cout << “Matrix B:” << endl;

printMatrix(matrixB);

cout << “Resultant Matrix after Addition:” << endl;

printMatrix(resultMatrix);

return 0;

}

Explanation