C++ Program to Find Inverse of a Given Matrix

  • First, calculate the determinant of the matrix.
  • Then calculate the adjoint of a given matrix. Adjoint can be obtained by taking the transpose of the cofactor matrix of a given square matrix.
  • Finally, multiply 1/deteminant by adjoint to get inverse.

C++ Program to Find Inverse of a Given Matrix

#include<iostream>
using namespace std;
int main(){
    int mat[3][3], i, j;
    float determinant = 0;
    cout<<"Enter elements of matrix row wise:\n";
    for(i = 0; i < 3; i++)
        for(j = 0; j < 3; j++)
           cin>>mat[i][j];
    
    printf("\nGiven matrix is:");
    for(i = 0; i < 3; i++){
        cout<<"\n";
        
        for(j = 0; j < 3; j++)
            cout<<mat[i][j]<<"\t";
    }
    
    for(i = 0; i < 3; i++)
        determinant = determinant + (mat[0][i] * (mat[1][(i+1)%3] * mat[2][(i+2)%3] - mat[1][(i+2)%3] * mat[2][(i+1)%3]));
    
    cout<<"\n\ndeterminant: "<<determinant;
    
    cout<<"\n\nInverse of matrix is: \n";
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++)
            cout<<((mat[(j+1)%3][(i+1)%3] * mat[(j+2)%3][(i+2)%3]) - (mat[(j+1)%3][(i+2)%3] * mat[(j+2)%3][(i+1)%3]))/ determinant<<"\t";
        
        cout<<"\n";
    }
 
   return 0;
}

Output Of Program

Enter elements of matrix row wise:
3
254
25
23
2
1
3
2
23

Given matrix is:
3 254 25
23 2 1
3 2 23

determinant: -132472

Inverse of matrix is:
-0.000332146 0.0437224 -0.00153995
0.00397065 4.52926e-005 -0.00431789
-0.000301951 -0.00570687 0.0440546