-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gauss_Elimination
100 lines (91 loc) · 2.12 KB
/
Gauss_Elimination
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
int main()
{
int n;
printf("Enter the number of variables: ");
scanf("%d", &n);
float A[n][n + 1];
float x[n + 1];
printf("Enter the elements of augmented matrix row-wise:\n");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= (n + 1); j++)
{
scanf("%f", &A[i][j]);
}
}
printf("\n");
int temp = 0;
if (A[1][1] == 0 && A[2][1] != 0)
{
for (int j = 1; j <= n + 1; j++)
{
temp = A[1][j];
A[1][j] = A[2][j];
A[2][j] = temp;
}
}
else if (A[1][1] == 0 && A[3][1] != 0)
{
for (int j = 1; j <= n + 1; j++)
{
temp = A[1][j];
A[1][j] = A[3][j];
A[3][j] = temp;
}
}
else if (A[1][1] == 0 && A[2][1] == 0 && A[3][1] == 0)
{
printf("Invalid Input\n");
}
printf("Augmented Matrix: \n");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n + 1; j++)
{
printf("%f ", A[i][j]);
}
printf("\n");
}
for (int j = 1; j <= n; j++) /* loop for the generation of upper triangular matrix*/
{
for (int i = 1; i <= n; i++)
{
if (i > j)
{
float c = A[i][j] / A[j][j];
for (int k = 1; k <= n + 1; k++)
{
A[i][k] = A[i][k] - c * A[j][k];
}
}
}
}
printf("\nUpper Triangular Matrix: \n");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n + 1; j++)
{
printf("%f ", A[i][j]);
}
printf("\n");
}
x[n] = A[n][n + 1] / A[n][n];
/* this loop is for backward substitution*/
for (int i = n - 1; i >= 1; i--)
{
float sum = 0.0;
for (int j = i + 1; j <= n; j++)
{
sum = sum + A[i][j] * x[j];
}
x[i] = (A[i][n + 1] - sum) / A[i][i];
}
printf("\nThe solution is:");
for (int i = 1; i <= n; i++)
{
printf("\n%d %f", i + 1, x[i]);
}
printf("\n");
return 0;
}