Matrix Inverse Using Gauss Jordan Method C Program
Earlier in Matrix Inverse Using Gauss Jordan Method Algorithm and Matrix Inverse Using Gauss Jordan Method Pseudocode , we discussed about an algorithm and pseudocode for finding inverse of matrix using Gauss Jordan Method. In this tutorial we are going to implement this method using C programming language.
Complete C Program for Matrix Inversion Using Gauss Jordan Method
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define SIZE 10
int main()
{
float a[SIZE][SIZE], x[SIZE], ratio;
int i,j,k,n;
clrscr();
/* Inputs */
/* 1. Reading order of matrix */
printf("Enter order of matrix: ");
scanf("%d", &n);
/* 2. Reading Matrix */
printf("Enter coefficients of Matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%f", &a[i][j]);
}
}
/* Augmenting Identity Matrix of Order n */
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
{
a[i][j+n] = 1;
}
else
{
a[i][j+n] = 0;
}
}
}
/* Applying Gauss Jordan Elimination */
for(i=1;i<=n;i++)
{
if(a[i][i] == 0.0)
{
printf("Mathematical Error!");
exit(0);
}
for(j=1;j<=n;j++)
{
if(i!=j)
{
ratio = a[j][i]/a[i][i];
for(k=1;k<=2*n;k++)
{
a[j][k] = a[j][k] - ratio*a[i][k];
}
}
}
}
/* Row Operation to Make Principal Diagonal to 1 */
for(i=1;i<=n;i++)
{
for(j=n+1;j<=2*n;j++)
{
a[i][j] = a[i][j]/a[i][i];
}
}
/* Displaying Inverse Matrix */
printf("\nInverse Matrix is:\n");
for(i=1;i<=n;i++)
{
for(j=n+1;j<=2*n;j++)
{
printf("%0.3f\t",a[i][j]);
}
printf("\n");
}
getch();
return(0);
}
Output
Enter order of matrix: 3 Enter coefficients of Matrix: a[1]1]= 1 a[1]2]= 1 a[1]3]= 3 a[2]1]= 1 a[2]2]= 3 a[2]3]= -3 a[3]1]= -2 a[3]2]= -4 a[3]3]= -4 Inverse Matrix is: 3.000 1.000 1.500 -1.250 -0.250 -0.750 -0.250 -0.250 -0.250
Recommended Readings