## Monday, 17 December 2012

### Gauss Elimination: C/C++ Program

Gauss elimination is one of the many operations we can perform on matrices. Here I have provided a program which finds the upper triangular matrix corresponding to the given matrix. It is often used to solve system of linear equations. Elementary row operations are used to obtain the upper triangular matrix in Gauss elimination method.

The C++ Program is given below.
```#include<iostream>
#define MAX 10
using namespace std;
int lcm(int x,int y);
int main()
{
int i,j,k,r,c,a[MAX][MAX],b[MAX][MAX],det=1,l,d1,d2;
cout<<"\nEnter the number of Rows of the Matrix: ";
cin>>r;
cout<<"\nEnter the number of Columns of the Matrix: ";
cin>>c;
if(r==c)
{
cout<<"\nEnter the Elements of the Matrix:\n";
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<r-1;i++)
{
for(j=i+1;j<r;j++)
{
l=lcm(a[i][i],a[j][i]);
if(l!=0&&(a[i][i]!=0&&a[j][i]!=0))
{
l=(a[i][i]*a[j][i])/l;
d1=l/a[i][i];
d2=l/a[j][i];
a[j][i]=0;
for(k=i+1;k<r;k++)
{
a[j][k]=(d2*a[j][k])-(d1*a[i][k]);
}
}
}
}
cout<<"\nThe given Matrix after Gauss Elimination is:\n";
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<"\n";
}
}
else
{
cout<<"\nThis is not a Square Matrix!!!\n";
}
return 0;
}
int lcm(int x,int y)
{
int t;
while (y != 0)
{
t=y;
y=x%y;
x=t;
}
return x;
}```

Figure Given Below Shows a 3 X 3 Matrix.

After Performing Gauss Elimination the Matrix is Shown Below.

1. 2. 3. 