Thursday, August 19, 2010

C Program Of NA Using Guass Sedial Method

//Gauss Seidal method
# include <stdio.h>
# include <conio.h>
# include <math.h>
# define MAXIT 50
# define EPS .000001
void main()
{
float a[10][10],b[10],x[10],sum,x0[10];
int i,j,n,count=0;
clrscr();
printf("Enter Number of equation : ");
scanf("%d",&n);
printf("Enter Coefficients row by row \n");
printf("One row in each line\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%f",&a[i][j]);
printf("Enter vector elements\n");
for(i=1;i<=n;i++)
{
x0[i]=x[i]=0;
scanf("%f",&b[i]);
}
printf("N\t");
for(i=1;i<=n;i++)
printf("X%d \t",i);
printf("\n");
printf("-------------------------------------------------------------------\n");
s: printf("%d\t",count+1);
for(i=1;i<=n;i++)
{
sum=0;
for(j=1;j<=n;j++)
{
if(i==j)
continue;
else
sum=sum+(a[i][j]*x[j]);
}
x[i]=(b[i]-sum)/a[i][i];
printf("%f \t",x[i]);
}
count++;
if(fabs(x[n]-x0[n])>EPS && count<MAXIT)
{
for(i=1;i<=n;i++)
x0[i]=x[i];
printf("\n");
goto s;
}
else
{
printf("\n----------------------------------------------\nSolution : \n");
for(i=1;i<=n;i++)
printf("X%d = %3.4f\t",i,x[i]);
}
getch();
}

OUTPUT

Enter Number of equation : 4
Enter Coefficients row by row
One row in each line
10 -2 -1 -1
-2 10 -1 -1
-1 -1 10 -2
-1 -1 -2 10
Enter vector elements
3 15 27 -9
N X1 X2 X3 X4
-------------------------------------------------------------------
1 0.300000 1.560000 2.886000 -0.136800
2 0.886920 1.952304 2.956562 -0.024765
3 0.983641 1.989908 2.992402 -0.004165
4 0.996805 1.998185 2.998666 -0.000768
5 0.999427 1.999675 2.999757 -0.000138
6 0.999897 1.999941 2.999956 -0.000025
7 0.999981 1.999989 2.999992 -0.000004
8 0.999997 1.999998 2.999999 -0.000001
9 0.999999 2.000000 3.000000 -0.000000
---------------------------------------------------------------------
Solution :
X1 = 1.0000 X2 = 2.0000 X3 = 3.0000 X4 = -0.0000

No comments:

Post a Comment