Wednesday, 7 November 2012

Gauss Elimination method (in C)



/*Gauss-Elimination Method for solving Simultaneous equations*/

#include<math.h>
#include<stdio.h>

void main()
{
       unsigned int n,i,r,j,k;
       float a[30][30],x[30],m,s,t;

       printf("****Gauss elimination Method****\n\n\n");
       printf("Enter number of equation:\n");
       scanf("%d",&n);
       printf("Enter the Augmented matrix :\n\n");
       for(i=1;i<=n;i++)
              for(j=1;j<=n+1;j++)
              {
                     scanf("%f",&a[i][j]);
              }

        for(k=1;k<n;k++)
     {
       m=abs(a[k][k]);
       r=k;
       for(i=k+1;i<=n;i++)
       {
        if(abs(a[i][k])>m)
          {
           m=abs(a[i][k]);
           r=i;
          }
       }
       for(j=1;j<=n+1;j++)
       {
        t=a[r][j];
        a[r][j]=a[k][j];
        a[k][j]=t;
        }
        for(i=k+1;i<=n;i++)
        {
           t=a[i][k]/a[k][k];
           for(j=1;j<=n+1;j++)
           a[i][j]=a[i][j]-a[k][j]*t;
        }              
    }
     for(i=n;i>=1;i--)
     {
      s=a[i][n+1];
      for(k=1;k<=n-i;k++)
      s=s-a[i][i+k]*x[i+k];
      x[i]=s/a[i][i];
      printf("\nthe %d th solution is x%d = %f",i,i,x[i]);
     }
     getch();
}



Results: (Gauss Elimination method)
****Gauss elimination Method****
Enter number of equation:
3
Enter the Augmented matrix :
2 1 1 5
3 5 2 15
2 1 4 8
the 3 th solution is x3 = 1.000000
the 2 th solution is x2 = 2.000000
the 1 th solution is x1 = 1.000000


NOTE: Compiler used Visual C++ express 2010





No comments:

Post a Comment