Tuesday 20 September 2011

Gauss Elimination Method


  /*Program for solution of system of linear solutions by Gauss Elimination  method*/

#include<stdio.h>
#include<conio.h>

void main()
{
  int status ,n,i,j;
  float a[10][10],b[10],x[10]t;
  clrscr();
  printf(“\n  SOLUTION  BY GAUSS ELIMINATION METHOD ”);
  printf(“ \n What is the size of the system  (n) ? \n”)
  scanf(“%d”, &n);
  printf(“\ Input coefficients a( i ,j ) , row- wise , \n  ”);
  printf(“ One row on each line \n”) ;
  for( i = 1; i<=n ; i++)
    for ( j=1; j<= n ; j++)
   {
     scanf (“ %f”, &t);
     a[i][j] = t;
    }
  printf(“ \n Input vector b \n”) ;
  for( i = 1; i<=n ; i++)
  {
    scanf (“ %f”, &t);
    b[i] = t;
   }
/ * Obtain solution by simple Gauss elimination method */
  gauss1 ( n,a,b,x, &status);
  if( status != 0)
  {
    printf(“\n SOLUTION VECTOR X \n”);
  for ( i = 1; i<=n ; i++)
     printf(“ % 10.6f ”, x[i]);
     printf(“\n”);
   }
   else
   {
    printf( “ singular matrix , reorder equation \n”);
    }
  getch();
  }
/ * End of main () program */

/* Defining subroutine gauss1( )  */
  gauss1 ( int n , float a[10][10],float b[10], float x[10], int *status)
  {
     int i,j,k;
     float pivot, factor ,sum;
     for(k = 1; k<= n-1; k++)
     {
       pivot a[k][k];
       if( fabs(pivot) < 0.000001 )
       {
         *status = 0;
           return ;
        }
        *status = 1;



         for( i=k+1;i<=n; i++)    
         {
           factor = a[i][k] / pivot;
           for ( j= k+1; j<=n; j++)
           {
             a[i][j] = a[i][j] – factor * a[k][j];
            }      
           b[i] = b[i] – factor * b[k];
         }
     }

 /* Back substitution begins */
   x[n]= b[n]/ a[n][n];
   for( k = n-1; k>= 1; k--)
   {
     sum = 0.0;
     for( j=k+1; j<=n ;j++)
       sum = sum + a[k][j]* x[j];
     x[k] = ( b[k] - sum) / a[k][k];
    }
   return ;
 }

No comments:

Post a Comment