Skip to content

Instantly share code, notes, and snippets.

@ry05
Created March 26, 2017 06:09
Show Gist options
  • Select an option

  • Save ry05/8ffea559ea42b4098cc220bd3ac22027 to your computer and use it in GitHub Desktop.

Select an option

Save ry05/8ffea559ea42b4098cc220bd3ac22027 to your computer and use it in GitHub Desktop.
Solving linear system of equations(Gauss Elimination)
#include <iostream.h>
int main()
{
cout<<"\t\t\t\t"<<"GAUSS ELIMINATION"<<endl;
int x,y,z;
int a1,b1,c1,a2,b2,c2,a3,b3,c3,d1,d2,d3;
cout<<"Enter the coeeficients of x,y,z in the same order for equation 1.Also enter the constant on RHS after that."<<endl;
cin>>a1>>b1>>c1>>d1;
cout<<"Enter the coeeficients of x,y,z in the same order for equation 2.Also enter the constant on RHS after that."<<endl;
cin>>a2>>b2>>c2>>d2;
cout<<"Enter the coeeficients of x,y,z in the same order for equation 3.Also enter the constant on RHS after that."<<endl;
cin>>a3>>b3>>c3>>d3;
int a[3][4]={a1,b1,c1,d1,a2,b2,c2,d2,a3,b3,c3,d3};
cout<<"The augmented matrix is :"<<endl<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
cout<<a[i][j]<<'\t';
}
cout<<endl;
}
for(i=0;i<3;i++)
{
if(i==1)
{
int j=0;
while(j<4)
{
int temp;
temp=(a1*a[1][j])-(a2*a[0][j]);
a[1][j]=temp;
j++;
}
}
}
for(i=0;i<3;i++)
{
if(i==2)
{
int j=0;
while(j<4)
{
int temp;
temp=(a1*a[2][j])-(a3*a[0][j]);
a[2][j]=temp;
j++;
}
}
}
int e=a[2][1];
int f=a[1][1];
for(i=0;i<3;i++)
{
if(i==2)
{
int j=0;
while(j<4)
{
int temp;
temp=(f*a[2][j])-(e*a[1][j]);
a[2][j]=temp;
j++;
}
}
}
cout<<"The row echelon form is :"<<endl;
for( i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
cout<<a[i][j]<<'\t';
}
cout<<endl;
}
int rank_A=3;
int cnt_zero1=0;
for(int j=0;j<3;j++)
{
if(a[0][j]==0)
cnt_zero1++;
}
if(cnt_zero1==3)
{
rank_A--;
}
int cnt_zero2=0;
for(j=0;j<3;j++)
{
if(a[1][j]==0)
cnt_zero2++;
}
if(cnt_zero2==3)
{
rank_A--;
}
int cnt_zero3=0;
for(j=0;j<3;j++)
{
if(a[2][j]==0)
cnt_zero3++;
}
if(cnt_zero3==3)
{
rank_A--;
}
int rank_AB=3;
int cnt_zero4=0;
for(int p=0;p<4;p++)
{
if(a[0][p]==0)
cnt_zero4++;
}
if(cnt_zero4==4)
{
rank_AB--;
}
int cnt_zero5=0;
for(p=0;p<4;p++)
{
if(a[1][p]==0)
cnt_zero5++;
}
if(cnt_zero5==4)
{
rank_AB--;
}
int cnt_zero6=0;
for(p=0;p<4;p++)
{
if(a[2][p]==0)
cnt_zero6++;
}
if(cnt_zero6==4)
{
rank_AB--;
}
cout<<"The rank of A is "<<rank_A<<endl<<"The rank of augmented matrix AB is "<<rank_AB<<endl;
int no_of_var=3;
if(rank_A!=rank_AB)
cout<<"The given system has no solution as rank(A) is not equal to rank(AB)"<<endl;
else if(rank_A==rank_AB)
{
if(rank_A<no_of_var)
cout<<"The given system has infinite solutions as rank(A)=rank(AB)< no. of unknowns"<<endl;
else
{
z=(a[2][3])/(a[2][2]);
y=(a[1][3]-(a[1][2]*z))/(a[1][1]);
x=(a[0][3]-(a[0][2]*z)-(a[0][1]*y))/a[0][0];
cout<<"The system has a unique solution given by:"<<endl;
cout<<"x: "<<x<<endl<<"y: "<<y<<endl<<"z: "<<z<<endl;
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment