Write a program to solve the system of equations Ax = b using Gauss-Seidel method

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
void main()
{
 float a[20][20],x[20],e,big,temp,relerror,sum;
 int n,i,j,maxit,itr;
 char ch;
 clrscr();
 printf("enter the size of the equation:");
 scanf("%d",&n);
 top:for(i=1;i<=n;i++)
    {
    printf("\n enter the co-efficient of the equation %d and rhs:\n",i);
    for(j=1;j<=n+1;j++)
    scanf("%f",&a[i][j]);
    }
 printf("\n enter the relative error and number of iteration:");
 scanf("%f%d",&e,&maxit);
  for(i=1;i<=n;i++)
  x[i]=0;
  for(itr=1;itr<=maxit;itr++)
  {
   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];
    relerror=fabs((x[i]-temp)/temp);
    if(relerror>big)
    big=relerror;
    x[i]=temp;
    }
    if(big<=e)
    {
     printf("\n converges to a solution \n");
     for(i=1;i<=n;i++)
     printf("%f\t",x[i]);
     getch();
     exit(1);
     }
    }
   printf("\n does not converge is %d iteration \n",maxit);
   printf("\n please try by interchanging any two equation \n");
   printf("make diagonal entries pivotal \n ");
   printf("\n do you want to try(y/n):");
   fflush(stdin);
   ch=getchar();
   if(ch=='y')
   goto top;
   for(i=1;i<=n;i++)
   printf("%f\t",x[i]);
   getch();
  }

No comments:

Post a Comment