33
Total Posts
3
Categories
24/7
Updated

C++

Write a program to find the matrix inversion by using Gauss-elimination method / Gauss Seidel method.

Published on Dec 22, 2025
Matrix Inversion (Gauss–Jordan Method)

 

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter order of matrix (n): ";
    cin >> n;

    float a[10][20], ratio;

    cout << "Enter elements of matrix:\n";
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> a[i][j];
        }
        // Append identity matrix
        for (int j = n; j < 2*n; j++) {
            a[i][j] = (i == (j - n)) ? 1 : 0;
        }
    }

    // Gauss-Jordan elimination
    for (int i = 0; i < n; i++) {
        if (a[i][i] == 0) {
            cout << "Matrix inversion not possible." << endl;
            return 0;
        }

        for (int j = 0; j < n; j++) {
            if (i != j) {
                ratio = a[j][i] / a[i][i];
                for (int k = 0; k < 2*n; k++) {
                    a[j][k] -= ratio * a[i][k];
                }
            }
        }
    }

    // Make diagonal elements 1
    for (int i = 0; i < n; i++) {
        float divisor = a[i][i];
        for (int j = 0; j < 2*n; j++) {
            a[i][j] /= divisor;
        }
    }

    // Output inverse matrix
    cout << "\nInverse Matrix is:\n";
    for (int i = 0; i < n; i++) {
        for (int j = n; j < 2*n; j++) {
            cout << a[i][j] << "\t";
        }
        cout << endl;
    }

    return 0;
}

Documentation

Input

Enter order of matrix (n): 2
Enter elements of matrix:
2 1
5 3

Output

Inverse Matrix is:
3   -1
-5  2

 

Idea (Gauss–Jordan Inversion)

  1. Start with matrix A

  2. Augment it with Identity matrix I[A | I]

  3. Use row operations to convert A → I

  4. The right side becomes A⁻¹