-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGaussElimination.cpp
79 lines (70 loc) · 1.61 KB
/
GaussElimination.cpp
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
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
#define SIZE 10
using namespace std;
int main()
{
float a[SIZE][SIZE], x[SIZE], ratio;
int i, j, k, n;
cout << setprecision(3) << fixed;
cout << "Enter number of unknowns: ";
cin >> n;
cout << "Enter Coefficients of Augmented Matrix: " << endl;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n + 1; j++)
{
cout << "a[" << i << "]" << j << "]= ";
cin >> a[i][j];
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
for (i = 1; i <= n - 1; i++)
{
if (a[i][i] == 0.0)
{
cout << "Mathematical Error!";
exit(0);
}
for (j = i + 1; j <= n; j++)
{
ratio = a[j][i] / a[i][i];
for (k = 1; k <= n + 1; k++)
{
a[j][k] = a[j][k] - ratio * a[i][k];
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
/* Obtaining Solution by Back Substitution Method */
x[n] = a[n][n + 1] / a[n][n];
for (i = n - 1; i >= 1; i--)
{
x[i] = a[i][n + 1];
for (j = i + 1; j <= n; j++)
{
x[i] = x[i] - a[i][j] * x[j];
}
x[i] = x[i] / a[i][i];
}
/* Displaying Solution */
cout << endl
<< "Solution: " << endl;
for (i = 1; i <= n; i++)
{
cout << "x[" << i << "] = " << x[i] << endl;
}
return (0);
}