C++ Program to Add Two Matrices

12/06/2024 0 By indiafreenotes

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

The resulting matrix after addition:

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);

    // Adding the two matrices

    vector<vector<int>> resultMatrix = addMatrices(matrixA, matrixB);

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

    printMatrix(resultMatrix);

    return 0;

}

Explanation

  1. Function addMatrices:
  • Parameters: Takes two 2D vectors (matrixA and matrixB).
  • Initialization: Initializes the result matrix with the same dimensions as the input matrices.
  • Element-wise Addition: Iterates through each element of the input matrices, sums the corresponding elements, and stores the result in the result matrix.
  1. Function printMatrix:

Prints the matrix in a formatted manner for better visualization.

  1. Main Function:

  • Initializes two sample 3×3 matrices (matrixA and matrixB).
  • Prints the original matrices.
  • Calls the addMatrices function to add the matrices.
  • Prints the resulting matrix after addition.