gaussian eliminaton c++ code example
Example: gaussian eliminaton c++
using namespace std;
int main() {
int n;
cout << "Enter the order of matrix:";
cin >> n;
float A[n][n+1];
float x[n];
for(int i=0;i<n;i++){
for(int j=0;j<n + 1;j++){
cout << "Enter matrix at a[" << i << "]" << "[" <<j << "]" << ": " ;
cin >> A[i][j];
}
}
//Upper triangular matrux
for(int j=0;j<n;j++){
for(int i=0;i<n;i++){
if(i>j){
float c = A[i][j] / A[j][j];
for(int k=0;k<n+1;k++){
A[i][k] = A[i][k] - c*A[j][k];
}
}
}
}
//Dividing each row
for(int i=1;i<n;i++){
float c = A[i][i];
for(int j=i;j<n+1;j++){
A[i][j] = A[i][j] / c;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n+1;j++){
cout << A[i][j] << " ";
}
cout << endl;
}
x[n-1] = A[n-1][n];
//backward substitution loop
for(int i=n-2;i>=0;i--){
float root = A[i][n];
for(int j = i+1; j<n ; j++){
root -= A[i][j] * x[j];
}
x[i] = root;
}
x[0] = x[0] / A[0][0];
for(int i=0; i<n; i++){
cout << x[i] << endl;;
}
return 0;
}