Stats

Friday, 7 September 2012

Gauss Elimination Method


# include<stdio.h>
# include<conio.h>
void main()
{
 int i,j,k,n;
 float a[10][10],x[10];
 float s,p; 
 printf("Enter the number of equations : ");
 scanf("%d",&n) ;
 printf("\nEnter the co-efficients of the equations :\n\n");
 for(i=0;i<n;i++)
 {
  for(j=0;j<n;j++)
  {
   printf("a[%d][%d]= ",i+1,j+1);
   scanf("%f",&a[i][j]);
  }
  printf("d[%d]= ",i+1);
  scanf("%f",&a[i][n]);
 }
 for(k=0;k<n-1;k++)
 {
  for(i=k+1;i<n;i++)
  {
   p = a[i][k] / a[k][k] ;
   for(j=k;j<n+1;j++)
    a[i][j]=a[i][j]-p*a[k][j];
  }
 }
 x[n-1]=a[n-1][n]/a[n-1][n-1];
 for(i=n-2;i>=0;i--)
 {
  s=0;
  for(j=i+1;j<n;j++)
  {
   s +=(a[i][j]*x[j]);
   x[i]=(a[i][n]-s)/a[i][i];
  }
 }
 printf("\nThe result is:\n");
 for(i=0;i<n;i++)
  printf("\nx[%d]=%f",i+1,x[i]);
 getch();

}

gauss seidel method

#include<stdio.h>
#include<conio.h>
#include<math.h>
#define e 0.01

void main() {
  int i, j, k, n;
  float a[10][10], x[10];
  float sum, temp, error, big;
  printf("Enter the number of equations: ");
  scanf("%d", & n);
  printf("Enter the co-efficients of the equations: \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]);
    }
  }
  for (i = 1; i <= n; i++) {
    x[i] = 0;
  }
  do {
    big = 0;
    for (i = 1; i <= n; i++) {
      sum = 0;
      for (j = 1; j <= n; j++) {
        if (j != i) {
          sum = sum + a[i][j] * x[j];
        }
      }
      temp = (a[i][n + 1] - sum) / a[i][i];
      error = fabs(x[i] - temp);
      if (error > big) {
        big = error;
      }
      x[i] = temp;
      printf("\nx[%d] =%f", i, x[i]);
    }
    printf("\n");
  }
  while (big >= e);
  printf("\n\nconverges to solution");
  for (i = 1; i <= n; i++) {
    printf("\nx[%d]=%f", i, x[i]);
  }
  getch();
}

Enter the number of equations: 3
Enter the co-efficients of the equations:
a[1][1]= 2
a[1][2]= 1
a[1][3]= 1
a[1][4]= 5
a[2][1]= 3
a[2][2]= 5
a[2][3]= 2
a[2][4]= 15
a[3][1]= 2
a[3][2]= 1
a[3][3]= 4
a[3][4]= 8

x[1] =2.500000
x[2] =1.500000
x[3] =0.375000

x[1] =1.562500
x[2] =1.912500
x[3] =0.740625

x[1] =1.173437
x[2] =1.999688
x[3] =0.913359

x[1] =1.043477
x[2] =2.008570
x[3] =0.976119

x[1] =1.007655
x[2] =2.004959
x[3] =0.994933

x[1] =1.000054
x[2] =2.001995
x[3] =0.999474


converges to solution
x[1]=1.000054
x[2]=2.001995
x[3]=0.999474