5. Write a program to demonstrate Gauss Seidel Method
/* Program to execute Gauss Seidel method*/
#include <stdio.h>
#include <math.h>
#define max 10
void main()
{
int i, j, k, count, maxitr, n;
float t = 0, d, sol, aerr, a[max][5], x[4], merr;
printf("Enter no. of equations \n");
scanf("%d", &n);
printf("Input data for augmented matrix:\n");
for (i = 0;
i < n;
i++)
{
for (j = 0; j <= n; j++)
{
scanf("%f", &a[i][j]);
}
}
for (i = 0; i < n; i++) /* Initialize array x to zero */
x[i] = 0;
printf("Enter the allowed error and maximum number of iterations: ");
scanf("%f %d", &aerr, &maxitr);
printf("\nIteration\tx[1]\t\tx[2]\t\tx[3]\t\tx[4]");
merr = 0;
for (count = 1; k count <= maxitr; count++)
{
for (i = 0; i < n; i++) /* Perform substitution */
{
sol = 0;
for (j = 0; j < n; j++)
{
if (j != i)
sol = sol + a[i][j] * x[j];
}
t = (a[i][n] - sol) / a[i][i];
d = fabs(x[i] - t);
tx[i] = t;
if (d > merr)
merr = d;
}
printf("\n %d\t", count);
for (i = 0; i < n; i++)
{
printf("\t%f", x[i]);
}
if (d < aerr) /* Check for allowed error */
{
printf("\n\nConverges after %d iterations", count);
printf("\n\nThe solution is:");
/* Print values */ for (i = 0; i < max; i++)
printf("\nElement %d: %f", i + 1, x[i]);
getch();
return;
}
}
printf("\nSolution does not converge, iterations not sufficient");
getch();
return;
}
Output
Enter no. of equations
4
Input data for augmented matrix:
10 -2 -1 -1 3
-2 10 -1 15
-1 -1 10 -2 27
-1 -1 -2 10 -9
Enter the allowed error and maximum number of iterations: 0.0001 15
iteration x[1] x[2] x[3] x[4]
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 0.999941 2.999956 -0.000025
7 0.999981 1.999989 2.999992 -0.000004
Converges after 7 iterations
The solution is:
Element 1: 0.999981
Element 1: 1.999989
Element 1: 0.2.999992
Element 1: -0.000004
Element 1: 10.000000
Element 1: -2.000000
Element 1: -1.000000
Element 1: -1.000000
Element 1: 3.000000
Element 1: -2.000000