C++ - Program - Add Two Matrices

#include <iostream>
#include <vector>
// Function to add two matrices
std::vector<std::vector<int>> addMatrices(const std::vector<std::vector<int>>& matrix1, const std::vector<std::vector<int>>& matrix2) {
    int rows = matrix1.size();
    int cols = matrix1[0].size();
    std::vector<std::vector<int>> result(rows, std::vector<int>(cols));
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
    return result;
}
// Function to display a matrix
void displayMatrix(const std::vector<std::vector<int>>& matrix) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }
}
int main() {
    // Define two matrices
    std::vector<std::vector<int>> matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    std::vector<std::vector<int>> matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
    // Add the matrices
    std::vector<std::vector<int>> result = addMatrices(matrix1, matrix2);
    // Display the matrices
    std::cout << "Matrix 1:" << std::endl;
    displayMatrix(matrix1);
    std::cout << "Matrix 2:" << std::endl;
    displayMatrix(matrix2);
    std::cout << "Resultant Matrix:" << std::endl;
    displayMatrix(result);
    return 0;
}

In this program, we define a function addMatrices that takes two matrices (matrix1 and matrix2) as input and returns their sum as a new matrix. The function uses nested loops to iterate over each element of the matrices and adds the corresponding elements together to calculate the sum.

The displayMatrix function is used to display a matrix to the console. It iterates over each element of the matrix and prints it.

In the main function, we define two matrices matrix1 and matrix2 and initialize them with values. We then call the addMatrices function to add the matrices and store the result in the result matrix. Finally, we display all three matrices (input matrices and the resultant matrix) using the displayMatrix function.