Write a program to solve the system of equations Ax = b using Gauss elimination method.

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
void main()
{
       float u,e,z,a[20][20],temp,x[20],sum,max;
       int m,n,j,i,p,k,q;
       clrscr();
       printf("enter the size of the equation");
       scanf("%d",&n);
       for(i=1;i<=n;i++)
             {
              printf("\n enter the co-eficient of the equation %d and RHS:\n",i);
              for(j=1;j<=n+1;j++)
              scanf("%f",&a[i][j]);
              }
       printf("\n enter the error allowed : \n");
       scanf("%f",&e);
       for(k=1;k<=n-1;k++)
         {
              max=abs(a[k][k]);
              p=k;
        for(m=k+1;m<=n;m++)
           {
              z=fabs(a[m][k]);
        if(z>max)
            {
               max=abs(a[m][k]);
               p=m;
             }
         }
   if(max<=e)
   {
          printf("ill conditional equation:");
          getch();
          exit(1);
   }
         if(p==k)goto cont;
         for(q=k;q<=n+1;q++)
               {
                temp=a[k][q];
                a[k][q]=a[p][q];
                a[p][q]=temp;
               }
        cont:for(i=k+1;i<=n;i++)
              {
               u=a[i][k]/a[k][k];
               for(j=k;j<=n+1;j++)
               a[i][j]=a[i][j]-u*a[k][j];
               }
               }
         x[n]=a[n][n+1]/a[n][n];
         printf("\nthe value of x%d is %f \n",n,x[n]);
         for(i=n-1;i>=1;i--)
               {
                sum=0;
          for(j=i+1;j<=n;j++)
          {
           sum=sum+a[i][j]*x[j];
           }
          x[i]=(a[i][n+1]-sum)/a[i][i];
          printf("\nthe value of x%2d is %f\n",i,x[i]);
          }
    getch();
}

No comments:

Post a Comment