GAUSS SEIDEL METHOD
July 22, 2022
Solve The Given Linear Equations Systems By Using Gauss Seidel Method
Source code :-
#include <stdio.h>#include <math.h>int main(){ int i, j, k, n, d, flag = 0, iteration = 0; float a[20][20], x[20], y[20], err, s; printf("Enter the number of equations: "); scanf("%d", &n); printf("\nEnter the correction upto decimal place: "); scanf("%d", &d); err = (5.0 / pow(10, d)); printf("\nEnter co-efficient matrix [A] row wise:\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("\na[%d][%d]= ", i + 1, j + 1); scanf("%f", &a[i][j]); } printf("\n"); } printf("\n\nEnter column matrix [B] row wise:\n"); for (i = 0, j = n; i < n; i++) { printf("\nb[%d]= ", i + 1); scanf("%f", &a[i][j]); } // Diagonaly dominant checking. for (i = 0; i < n; i++) { s = 0.0; for (j = 0; j < n; j++) { if (i == j) continue; s = s + (fabs(a[i][j])); } if ((fabs(a[i][i])) < s) { printf("\nThe entered system of linear equeation is not diagonaly dominant.\n"); return 1; } } for (i = 0; i < n; i++) { x[i] = 0.0; y[i] = 0.0; } do { iteration++; printf("\n\nIteration: %d\n\n", iteration); for (i = 0; i < n; i++) { x[i] = a[i][n]; for (j = 0; j < n; j++) { if (i == j) continue; x[i] = x[i] - a[i][j] * x[j]; } x[i] = x[i] / a[i][i]; } for (i = 0; i < n; i++) { flag = 0; if ((fabs(x[i] - y[i])) > err) { flag = 1; for (j = 0; j < n; j++) { y[j] = x[j]; } break; } } for (j = 0; j < n; j++) { printf("x[%d]=%f\t", j + 1, x[j]); } } while (flag == 1); printf("\n\nThe solution is:\n"); for (i = 0; i < n; i++) { printf("x[%d]=%f\n", i + 1, x[i]); } return 1;}
Input-Output :-
abhi@hp-15q-laptop:~$ gcc gauss_seidel.cabhi@hp-15q-laptop:~$ ./a.out
Enter the number of equations: 3
Enter the correction upto decimal place: 5
Enter co-efficient matrix [A] row wise:
a[1][1]= 4
a[1][2]= -1
a[1][3]= -1
a[2][1]= -2
a[2][2]= 6
a[2][3]= 1
a[3][1]= -1
a[3][2]= 1
a[3][3]= 7
Enter column matrix [B] row wise:
b[1]= 3
b[2]= 9
b[3]= -6
Iteration: 1
x[1]=0.750000 x[2]=1.750000 x[3]=-1.000000
Iteration: 2
x[1]=0.937500 x[2]=1.979167 x[3]=-1.005952
Iteration: 3
x[1]=0.993304 x[2]=1.998760 x[3]=-1.000780
Iteration: 4
x[1]=0.999495 x[2]=1.999961 x[3]=-1.000067
Iteration: 5
x[1]=0.999974 x[2]=2.000002 x[3]=-1.000004
Iteration: 6
x[1]=1.000000 x[2]=2.000000 x[3]=-1.000000
The solution is:x[1]=1.000000x[2]=2.000000x[3]=-1.000000