Menu Close

Gauss Elimination Method C++

#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;
#define N 4

int main()
{
float a[N][N+1],x[N],t,s;
int i,j,k;

cout<<"Enter the elements of the";
cout<<" augmented matrix rowwise"<<endl;
cout<<fixed;

for(i=0;i<N;i++)
for(j=0;j<N+1;j++)
cin>>a[i][j];
for(j=0;j<N-1;j++)
for(i=j+1;i<N;i++)
{
t=a[i][j]/a[j][j];
for(k=0;k<N+1;k++)
a[i][k] -= a[j][k]*t;
}

//Now printing the upper triangular matrix

cout<<"The upper triangular matrix is:-"<<endl;

for(i=0;i<N;i++)
{
for(j=0;j<N+1;j++)
cout<<setw(8)<<setprecision(4)<<a[i][j];
cout<<endl;
}

//Now performing back substitution

for(i=N-1;i>=0;i--)
{
s=0;
for(j=i+1;j<N;j++)
s += a[i][j]*x[j];
x[i]=(a[i][N]-s)/a[i][i];
}

//Now printing the results

cout<<"The solution is:-"<<endl;

for(i=0;i<N;i++)
{cout<<"x["<<setw(3)<<i+1<<"]=";
cout<<setw(7)<<setprecision(4)<<x[i]<<endl;}

return 0;
}

Output

Enter the elements of the augmented matrix rowwise
10 -6 3 5 6
-6 8 -2 -4 5
3 2 4 11 2
5 -9 -2 3 7
10 -6 3 5 6

-6 8 -2 -4 5

3 2 4 11 2

5 -9 -2 3 7
The upper triangular matrix is:-
10.0000 -6.0000 3.0000 5.0000 6.0000
0.0000 4.4000 -0.2000 -1.0000 8.6000
0.0000 0.0000 3.2727 10.3636 -7.2273
0.0000 0.0000 0.0000 11.0833 7.3958
The solution is:-
x[ 1]= 2.7086
x[ 2]= 1.9098
x[ 3]=-4.3214
x[ 4]= 0.6673

More Related Stuff