Gauss Jordan Method Using C Programming

Earlier in Gauss Jordan Method Algorithm and Gauss Jordan Method Pseudocode , we discussed about an algorithm and pseudocode for solving systems of linear equation using Gauss Jordan Method. In this tutorial we are going to implement this method using C programming language.

Complete Program for Gauss Jordan method using C Programming Language


#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 number of unknowns */
		 printf("Enter number of unknowns: ");
		 scanf("%d", &n);
		 /* 2. Reading Augmented Matrix */
		 printf("Enter coefficients of Augmented Matrix:\n");
		 for(i=1;i<=n;i++)
		 {
			  for(j=1;j<=n+1;j++)
			  {
				   printf("a[%d][%d] = ",i,j);
				   scanf("%f", &a[i][j]);
			  }
		 }
		 /* 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<=n+1;k++)
					    {
					     	a[j][k] = a[j][k] - ratio*a[i][k];
					    }
				   }
			  }
		 }
		 /* Obtaining Solution */
		 for(i=1;i<=n;i++)
		 {
		  	x[i] = a[i][n+1]/a[i][i];
		 }
		 /* Displaying Solution */
		 printf("\nSolution:\n");
		 for(i=1;i<=n;i++)
		 {
		  	printf("x[%d] = %0.3f\n",i, x[i]);
		 }
		 getch();
		 return(0);
}
Output: Gauss Jordan Method for Solving Systems of Linear Equations

Output

Enter number of unknowns: 4
Enter Coefficients of Augmented Matrix:
a[1]1]= 1
a[1]2]= 2
a[1]3]= 3
a[1]4]= -1
a[1]5]= 10
a[2]1]= 2
a[2]2]= 3
a[2]3]= -3
a[2]4]= -1
a[2]5]= 1
a[3]1]= 2
a[3]2]= -1
a[3]3]= 2
a[3]4]= 3
a[3]5]= 7
a[4]1]= 3
a[4]2]= 2
a[4]3]= -4
a[4]4]= 3
a[4]5]= 2

Solution:
x[1] = 1.000
x[2] = 2.000
x[3] = 2.000
x[4] = 1.000

Recommended Readings

  1. Gauss Jordan Method Algorithm
  2. Gauss Jordan Method Pseudocode
  3. Gauss Jordan Method Using C
  4. Gauss Jordan Method Using C++