Cover Image for Add Two Matrix in C++
140 views

Add Two Matrix in C++

To add two matrices in C++, you’ll need to make sure that they have the same dimensions (i.e., same number of rows and columns). Here’s a C++ program that demonstrates how to add two matrices:

#include <iostream>
#include <vector>

std::vector<std::vector<int>> addMatrices(const std::vector<std::vector<int>>& A, const std::vector<std::vector<int>>& B) {
    int rows = A.size();
    int cols = A[0].size();

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

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

    return result;
}

void printMatrix(const std::vector<std::vector<int>>& matrix) {
    for (const auto& row : matrix) {
        for (int element : row) {
            std::cout << element << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    std::vector<std::vector<int>> A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    std::vector<std::vector<int>> B = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};

    if (A.size() == B.size() && A[0].size() == B[0].size()) {
        std::vector<std::vector<int>> sum = addMatrices(A, B);

        std::cout << "Matrix A:" << std::endl;
        printMatrix(A);

        std::cout << "Matrix B:" << std::endl;
        printMatrix(B);

        std::cout << "Sum of matrices A and B:" << std::endl;
        printMatrix(sum);
    } else {
        std::cout << "Error: Matrices must have the same dimensions for addition." << std::endl;
    }

    return 0;
}

In this program:

  • The function addMatrices takes two matrices A and B as input and returns a new matrix that represents their sum.
  • It first checks if the dimensions of A and B are compatible for addition.
  • It then creates a result matrix with the same dimensions as the input matrices.
  • It iterates through each element of A and B, adding the corresponding elements and storing the result in the corresponding position of the result matrix.
  • The function printMatrix is used to print a matrix to the console.
  • In the main function, two example matrices A and B are defined and then added together. The result is printed to the console.

Make sure that both matrices have the same number of rows and columns for successful addition.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS