Skip to content

Instantly share code, notes, and snippets.

@pa1pal
Created September 29, 2015 19:12
Show Gist options
  • Save pa1pal/bfd83fed5e12fb29f858 to your computer and use it in GitHub Desktop.
Save pa1pal/bfd83fed5e12fb29f858 to your computer and use it in GitHub Desktop.
Guass elimination method
#include<iostream>
#include<cmath>
using namespace std;
/*
Function to print the matrix
*/
void print(double **a, int unk, int eq)
{
for( int i=0;i<eq;i++)
{
for( int j=0; j<=unk; j++)
{
if(j==0)
cout<<"\n\n";
cout<<a[i][j]<<" ";
}
}
}
int main()
{
char y;
do
{
int n,m,steps=0,z=2;
int unk, eq;
cout<<"Enter the value of unkown variables and number of equations\n";
cin>>unk>>eq;
double c,value;
double **a = new double *[eq]; //dynamic 2D array
for(int i=0;i<eq;i++)
{
a[i] = new double[unk+1];
for(int j=0; j<=unk; j++)
{
cin>>a[i][j];
}
}
print(a,unk,eq);
/*
Actual logic
*/
for(int i=0;i<eq;i++)
{
value = a[i][i]; //storing the diagonal value otherwise it will change in operations
for(int j=i;j<=unk;j++)
{
a[i][j] /= value; //first of all make diagonal values one
}
//secondly, subtracting rows values by multiplying to the diagonal value
for(int k=i;k<=unk;k++)
{
for (int l = 1; l <eq; ++l)
{
a[i+l][k] -= (a[i+l][k] * a[i][k]);
}
}
//break;
//you can use the break to see the output of 1st iteration.
}
print(a,unk,eq);
cout<<"Want to solve more equations\n Press 'y' or 'Y' for yes and any other key for no\n";
cin>>y;
}while(y=='y' || y=='Y');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment