How to subtract two matrices (matrix) in C++

1 Answer

0 votes
#include <iostream>

#define COLS 4

 void SubtractMatrices(int matrix1[][COLS], int matrix2[][COLS], int sub[][COLS], int rows, int cols) {
     for (int i = 0; i < rows; i++)
         for (int j = 0; j < cols; j++)
             sub[i][j] = matrix1[i][j] - matrix2[i][j];
}

int main()
{
    int matrix1[][COLS] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 7, 6, 3 } };
    int matrix2[][COLS] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 } };
    int sub[][COLS] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };

    int rows = sizeof(matrix1) / sizeof(matrix1[0]);
    int cols = sizeof(matrix1[0]) / sizeof(matrix1[0][0]);

    SubtractMatrices(matrix1, matrix2, sub, rows, cols);

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            std::cout << sub[i][j] << " ";
        std::cout << "\n";
    }
}



/*
run:

0 1 2 3 
3 4 5 6 
6 4 3 0 

*/

 



answered Oct 3, 2022 by avibootz

Related questions

2 answers 183 views
183 views asked Jul 6, 2020 by avibootz
1 answer 106 views
1 answer 122 views
1 answer 126 views
1 answer 123 views
1 answer 110 views
1 answer 114 views
...