subtraction of a 2d matrix in c++

To subtract two 2D matrices in C++, you can follow the steps below:

  1. Declare the matrices: Start by declaring two 2D matrices, let's call them matrix1 and matrix2, of the same size. You can declare them as arrays of arrays or as vectors of vectors.

  2. Initialize the matrices: Assign values to the elements of both matrices. This can be done manually or using loops to iterate over the rows and columns of the matrices and assign values.

  3. Create a result matrix: Declare another 2D matrix, let's call it resultMatrix, with the same size as the input matrices to store the result of the subtraction.

  4. Perform the subtraction: Use nested loops to iterate over the rows and columns of the input matrices. Subtract the corresponding elements of matrix1 and matrix2 and store the result in the corresponding position of resultMatrix. The subtraction can be done using the - operator.

  5. Display the result: Finally, iterate over the rows and columns of resultMatrix and print the elements to display the resulting matrix.

Here's an example code snippet that demonstrates the subtraction of two 2D matrices:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    // Declare and initialize the input matrices
    vector<vector<int>> matrix1 = {{1, 2, 3},
                                   {4, 5, 6},
                                   {7, 8, 9}};
    vector<vector<int>> matrix2 = {{9, 8, 7},
                                   {6, 5, 4},
                                   {3, 2, 1}};

    // Create a result matrix
    vector<vector<int>> resultMatrix(matrix1.size(), vector<int>(matrix1[0].size()));

    // Perform the subtraction
    for (int i = 0; i < matrix1.size(); i++) {
        for (int j = 0; j < matrix1[0].size(); j++) {
            resultMatrix[i][j] = matrix1[i][j] - matrix2[i][j];
        }
    }

    // Display the result
    cout << "Result matrix:" << endl;
    for (int i = 0; i < resultMatrix.size(); i++) {
        for (int j = 0; j < resultMatrix[0].size(); j++) {
            cout << resultMatrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

This code declares two matrices matrix1 and matrix2, initializes them with values, subtracts them element-wise, and stores the result in resultMatrix. Finally, it displays the resulting matrix resultMatrix.