# Gaussian elimination in C++

In this tutorial, we will learn how to solve linear equations using Gaussian elimination in C++.  Before proceeding further let’s first understand what is Gaussian elimination.

Gaussian elimination: it is an algorithm in linear algebra that is used to solve linear equations. In gaussian elimination, we transform the augmented matrix into row echelon form and perform the backward substitution to discover the values of unknowns.

Augmented matrix:

Row echelon form: a matrix is in row echelon form if

1. All rows with at least one nonzero element are above all-zero rows (if any).
2. The first nonzero number from the left of a nonzero row is at the right of the leading coefficient of the row above it.

For example:

## Program to solve linear equations using Gaussian elimination in C++

```#include<iostream>
/* math.h header file is included for abs() function */
#include<math.h>
using namespace std;

int main()
{
int i,j,k,n;

cout<<"\nEnter the no. of equations: ";
cin>>n;

/* if no of equations are n then size of augmented matrix will be n*n+1. So here we are declaring 2d array 'mat' of size n+n+1 */
float mat[n][n+1];

/* for n equations there will be n unknowns which will be stored in array 'res' */
float res[n];

cout<<"\nEnter the elements of the augmented matrix: ";
for(i=0;i<n;i++)
{
for(j=0;j<n+1;j++)
{
cin>>mat[i][j];
}
}

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(abs(mat[i][i]) < abs(mat[j][i]))
{
for(k=0;k<n+1;k++)
{
/* swapping mat[i][k] and mat[j][k] */
mat[i][k]=mat[i][k]+mat[j][k];
mat[j][k]=mat[i][k]-mat[j][k];
mat[i][k]=mat[i][k]-mat[j][k];
}
}
}
}

/* performing Gaussian elimination */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
float f=mat[j][i]/mat[i][i];
for(k=0;k<n+1;k++)
{
mat[j][k]=mat[j][k]-f*mat[i][k];
}
}
}

/* Backward substitution for discovering values of unknowns */
for(i=n-1;i>=0;i--)
{
res[i]=mat[i][n];

for(j=i+1;j<n;j++)
{
if(i!=j)
{
res[i]=res[i]-mat[i][j]*res[j];
}
}
res[i]=res[i]/mat[i][i];
}

cout<<"\nThe values of unknowns for the above equations=>\n";
for(i=0;i<n;i++)
{
cout<<res[i]<<"\n";
}

return 0;
}```

Input/Output:

```Enter the no. of equations: 2

Enter the elements of the augmented matrix:
3 -1 7
2 3 1

The values of unknowns for the above equations=> 2 -1```

You may also learn:

### 4 responses to “Gaussian elimination in C++”

1. Andrey Neyvanov says:

It seems if(i!=j) is not needed.

2. SynZiemiPolskiejAZarazemJa says:

This mumbo-jumbo in lines 37-39 should be replaced with one call to std::swap, like so:
std::swap(mat[i][k], mat[j][k]).
It will be much more readable this way.

3. Patrick DiRusso says:

line 50: division by zero if the linear system has identical rows… column has no non-zero pivots; infinitely many solutions via free var or none at all

4. Patrick DiRusso says:

agree with SynZiemiPolskiejAZarazemJa…….

perhaps linear search down the column for the largest pivot in abs.value
….only 1 row swap needed using a temp var or library swap