Tuesday 20 September 2011

Gauss Seidel Iterative Method


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

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

void main()
{
  int n,i,j,k,l,nit;
  float a[10][10],b[10],x[10],x1[10],t;
  clrscr();
  printf(“Give no. of variables ”);
  scanf(“%d”, &n);
  for(i=0;i<=n;i++)
  {
     for(j=0;j<n;j++)  {
         printf(“%d ,%d   th coefficient wanted ” , i+1 ,j+1);
         scanf(“%f ”, &a[i][j]);
      }
      printf(“%d th constant wanted ”, i+1);
      scanf(“%f ”, &b[i]);
   }

/* Solution started*/
 for(i=0;i<=n;i++)
 {
     t = fabs(a[i][j]);
     k = i ;
     for(j=i+1;j<n; j++)
        if (fabs ( a[i][j] >t))
        {
          k = j;
          t = fabs ( a[j][i] );
         }
         if( t< 1e - 5){
            printf(“Almost singular matrix, solution not possible\n”);
            exit(0);
         }
         if (i!= k)
            for(l=0;l<n;l++){
                t = a[i][l];
                a[i][l] = a[k][l];
                a[k][l]= t;
                t = b[i] ;
                b[i]= b[l];
                b[l] = t;
             }
     }
     for(i=0;i<=n;i++)
     x[i] = 0;
     nit = 0;
     while(i)
     {
        for(i=0;i<=n;i++)
        {
           t = b[i] ;
           for(l=0;l<n;l++)
               if(l<i) t-=a[i][l] *x1[l];
               else
               if( l>i)t-= a[i][l] *x1[l];

               x1[i]= t/ a[i][i];
        }
        t = 0;
        for(l=0;l<n; l++)
        t += (x i [l] – x[l] ) * ( x1 [l] – x[l]) ;
        if (t< le -5) break;
        nit ++;
        if( nit >30)
       {
          printf(“Divergent\n”);
          exit(1);
         }
        for(l=0;l<n; l++)
        x [l] = x1 [l];
     }
    printf(“ Solution are \n”)  ;
    for( i=0 ; i< n ; i++)
    printf(“ x[%d]= %f \n”,i, x1[i]);
    getch();
  }

4 comments:

  1. Thanks.
    http://studentcorner-bd.blogspot.com/

    ReplyDelete
  2. in line t = fabs(a[i][j]);
    you are using j but j has not been defined

    ReplyDelete
    Replies
    1. J has been defined after void main. i.e. 3rd variable integer.
      void main()
      {
      int n,i,j,k,l,nit;

      Delete
  3. Is there a way to do this method

    ReplyDelete