Wednesday, 12 December 2012

Gauss Seidel iterative method





       §       /*Gauss Seidel iterative method*/
#include<stdio.h>
#include<conio.h>
void main()
{
     int c(float *x,float *x1,int n,float e);
     float mod(float n),e;
     printf("values of leading dia 0f the coefficient matrix should be larger than others:\n");
     printf("enter the value of tolerance:\n");
     scanf("%f",&e);
     int i,j,s,k,n;
     printf("enter the max no of successive itterations to be performed in any case:\n");
     scanf("%d",&s);
     printf("enter the no of unknowns:\n");
     scanf("%d",&n);
     float a[n][n+1];
     printf("enter the elements of the augmented matrix rowwise:\n");
     for(i=0;i<n;i++)
     {
                      for(j=0;j<n+1;j++)
                      scanf("%f",&a[i][j]);
     }
     float x[n],x1[n];
     for(i=0;i<n;i++)
     x[i]=x1[i]=0;
     k=0;
     do
     {
         for(i=0;i<n;i++)
         x1[i]=x[i];
         for(i=0;i<n;i++)
         {
                         x[i]=a[i][n];
                          for(j=0;j<n;j++)
                         {
                                         if(j!=i)
                                         x[i]=x[i]-a[i][j]*x[j];
                         }
                         x[i]=x[i]/a[i][i];
        
         }    
         k++;
     }
     while(k<=s && c(x,x1,n,e));
     printf("the solution is:\n");
     for(i=0;i<n;i++)
     printf("x%d=%f\n",i+1,x[i]);
     getch();
}
int c(float *x,float *x1,int n,float e)
{
    int i;
    for(i=0;i<n;i++)
    {
                 if(e<mod(*(x+i)-*(x1+i)))
                 return(1);
    }
    return(0);
}
float mod(float n)
{                                                                              
      if(n<=0)
      return(-n);
      else
      return(n);
}