c program to solve a system of equation using matrix inversion method

 #include <stdio.h>

#include <stdlib.h>
int main()
{
    double A[3][3], B[3][1];
    int n;
    printf("\nEnter size of square Matrix: ");
    scanf("%d", &n);
    printf("\nEnter elements of first Matrix:\n");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            scanf("%lf", &A[i][j]);
        }
    }
    printf("\nEnter elements of second Matrix:\n");
    for (int j = 0; j < n; j++)
        scanf("%lf", &B[j][0]);
    double inverse[3][3], mul[3][1];
    double det = A[0][0] * (A[1][1] * A[2][2] - A[2][1] * A[1][2]) -
                 A[0][1] * (A[1][0] * A[2][2] - A[2][0] * A[1][2]) +
                 A[0][2] * (A[1][0] * A[2][1] - A[2][0] * A[1][1]);
    // Check if the determinant is non-zero
    if (det == 0)
    {
        printf("The matrix is singular, and its inverse does not exist.\n");
        exit(EXIT_FAILURE);
    }

    // Calculate the adjugate of the matrix
    else
    {
        double adjugate[3][3];
        adjugate[0][0] = A[1][1] * A[2][2] - A[1][2] * A[2][1];
        adjugate[0][1] = A[0][2] * A[2][1] - A[0][1] * A[2][2];
        adjugate[0][2] = A[0][1] * A[1][2] - A[0][2] * A[1][1];
        adjugate[1][0] = A[1][2] * A[2][0] - A[1][0] * A[2][2];
        adjugate[1][1] = A[0][0] * A[2][2] - A[0][2] * A[2][0];
        adjugate[1][2] = A[0][2] * A[1][0] - A[0][0] * A[1][2];
        adjugate[2][0] = A[1][0] * A[2][1] - A[1][1] * A[2][0];
        adjugate[2][1] = A[0][1] * A[2][0] - A[0][0] * A[2][1];
        adjugate[2][2] = A[0][0] * A[1][1] - A[0][1] * A[1][0];

        // Calculate the inverse by dividing the adjugate by the determinant
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                inverse[i][j] = adjugate[i][j] / det;
            }
        }
    }
    double result[3][1];
    for (int i = 0; i < n; i++)
    {
        result[i][0] = 0;
        for (int j = 0; j < n; j++)
        {
            result[i][0] += inverse[i][j] * B[j][0];
        }
    }
    printf("\nResultant Matrix is : \n");
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < 1; j++)
        {
            printf("%.2lf\t", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Comments

Popular Posts