-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGaussElimination.c
50 lines (42 loc) · 1.23 KB
/
GaussElimination.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Contributed by - Anuj Das ( GC University, Silchar - @ Department of Computer Science )
/* 8. Write a C program to solve the following set of equations by Gauss Elimination Method:
2.x1 + 4.x2 + 2.x3 = 15
2.x1 + x2 + 2.x3 = -54
x1 + x2 - 2.x3 = 0
*/
#include <stdio.h>
#include <stdlib.h>
void main() {
int n = 3, i, j, k; // Number of unknowns
double A[n][n+1]; // Augmented Matrix
double x[n]; // Solution
printf("Enter the Augmented Matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j <= n; j++) {
scanf("%lf", &A[i][j]);
}
}
// Gaussian Elimination
for (k = 0; k < n - 1; k++) {
for ( i = k + 1; i < n; i++) {
double factor = A[i][k] / A[k][k];
for (j = k; j <= n; j++) {
A[i][j] -= factor * A[k][j];
}
}
}
// Back Substitution
x[n - 1] = A[n - 1][n] / A[n - 1][n - 1];
for (i = n - 2; i >= 0; i--) {
double sum = 0.0;
for (j = i + 1; j < n; j++) {
sum += A[i][j] * x[j];
}
x[i] = (A[i][n] - sum) / A[i][i];
}
// Print Solution
printf("\nThe Solution is:\n");
for (i = 0; i < n; i++) {
printf("x%d: %lf\n", i + 1, x[i]);
}
}