How to inverse N x M matrix in C++

1 Answer

0 votes
#include <iostream>
#include <iomanip>

#define ROWS 3
#define COLS 4

void printMatrix(int matrix[][COLS], int rows, int cols) {
    for (int i = 0; i < rows; i++) {  
        for (int j = 0; j < cols; j++) {
            std::cout << std::setw(4) << matrix[i][j];
        } 
        std::cout << "\n";
    }
}

void inverseMatrix(int m[][COLS], int rows, int cols) {
    int i, j, r, c, tmp, counter = 0;
      
    for (r = rows - 1, i = 0; i < rows; i++, r--) {
        for (c = cols - 1, j = 0; j < cols; j++, c--) {
              tmp = m[i][j];
              m[i][j] = m[r][c];
              m[r][c] = tmp;
              counter++;
              if (counter > (rows * cols) / 2 - 1) return; 
        }
    }
}

int main(void)
{
    int i, j, matrix[ROWS][COLS] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
     
    printf("matrix:\n");
    printMatrix(matrix, ROWS, COLS);
    
    inverseMatrix(matrix, ROWS, COLS);
    
    printf("\ninverse matrix:\n");
    printMatrix(matrix, ROWS, COLS);

    return 0;
}


 
/* 
run:
 
matrix:
   1   2   3   4
   5   6   7   8
   9  10  11  12

inverse matrix:
  12  11  10   9
   8   7   6   5
   4   3   2   1
 
*/

 



answered May 16, 2024 by avibootz

Related questions

...