CALCULATING INVERSE MATRIX


include "stdafx.h"
#include "iostream"
#define N 4
using namespace std;

void main(){
       int i, j, k;
       double **A, **B, **X;
       A = new double *[N + 1];
       B = new double *[N + 1];
       X = new double *[N + 1];
       for (i = 0; i <= N; i++){
             A[i] = new double[N + 1];
             B[i] = new double[N + 1];
             X[i] = new double[N + 1];
       }
       cout << "Enter values for matrix A:" << endl;
       cout << "a11=" << endl;
       cin >> A[1][1];
       cout << "a12=" << endl;
       cin >> A[1][2];
       cout << "a13=" << endl;
       cin >> A[1][3];
       cout << "a14=" << endl;
       cin >> A[1][4];
       cout << "a21=" << endl;
       cin >> A[2][1];
       cout << "a22=" << endl;
       cin >> A[2][2];
       cout << "a23=" << endl;
       cin >> A[2][3];
       cout << "a24=" << endl;
       cin >> A[2][4];
       cout << "a31=" << endl;
       cin >> A[3][1];
       cout << "a32=" << endl;
       cin >> A[3][2];
       cout << "a33=" << endl;
       cin >> A[3][3];
       cout << "a34=" << endl;
       cin >> A[3][4];
       cout << "a41=" << endl;
       cin >> A[4][1];
       cout << "a42=" << endl;
       cin >> A[4][2];
       cout << "a43=" << endl;
       cin >> A[4][3];
       cout << "a44=" << endl;
       cin >> A[4][4];
       cout << "The matrix A[" << N << "x" << N << "]:" << endl;
       for (i = 1; i <= N; i++){
             for (j = 1; j <= N; j++)
             {
                    cout << A[i][j] << " ";
                    if (i == j)
                           B[i][j] = 1;
                    else
                           B[i][j] = 0;
             }
             cout << endl;
       }
       /*Operations of rows*/
       double Sum, m;
       for (k = 1; k <= N - 1; k++)
             for (i = k + 1; i <= N; i++)
             {
                    m = A[i][k] / A[k][k];
                    for (j = 1; j <= N; j++)
                    {
                           A[i][j] -= m*A[k][j];
                           B[i][j] -= m*B[k][j];
                    }
             }
       /*Backward supstitution*/
       for (i = N; i >= 1; i--)
             for (j = 1; j <= N; j++)
             {
                    Sum = 0;
                    for (k = i + 1; k <= N; k++)
                           Sum += A[i][k] * X[k][j];
                    X[i][j] = (B[i][j] - Sum) / A[i][i];
             }
       cout << "The inverse matrix is X[4X4]:" << endl;
       for (i = 1; i <= N; i++){
             for (j = 1; j <= N; j++){
                    cout << X[i][j] << " ";
             }
             cout << endl;
       }
       system("pause");
}


Share on Google Plus