C++ Program for Determinant of a Matrix using Gauss Elimination

cpp cplusplus plus c
So I wrote a code for Gaussian Elimination to solve a system of linear equations a while ago.
But recently learned that it has two further useful applications.
That is, the matrix obtained is an Upper Triangular Matrix and thus can be used for the LU-Decomposition
and that this LU Decomposition can be used to calculate the determinant of the matrix.

Let me explain the underlying theory in brief.

The process of Gaussian Elimination converts the given matrix into an Upper Triangular matrix U. Now the good thing about triangular matrices is that their determinant is equal to the product of the elements on the diagonal.
Another thing to note is that this procedure of gaussian elimination gives us another matrix L, which is lower triangular and has unit diagonal entries. So its determinant is effectively 1.
Now the best part is that the product of L and U gives us a permutation of the original matrix A.
What I mean by permutation of A is that the rows are the same as the original matrix A but their order is changed.

Now with all this information the determinant can be easily calculated.
The determinant is simply equal to det(A)=(-1)mdet(L)*det(U) where m is the number of row iterchanges that took place for pivoting of the matrix, during gaussian elimination. Since the determinant changes sign with every row/column change we multiply by (-1)^m.

Also since the L has only unit diagonal entries it’s determinant is equal to one.

So all we need is the determinant of U and m.
Therefore, det(A)=(-1)^mdet(U)

The following code does all of this and prints the determinant.

using namespace std;
int main()
    int n,i,j,k;
    cout.precision(4);        //set precision
    cout<<"\nEnter the order(n): \n";        
    cin>>n;                //input the no. of equations
    float a[n][n];        //declare an array to store the elements of augmented-matrix  
	double det=1; 
	int flag=0; 
    cout<<"\nEnter the elements of the matrix row-wise:\n";
    for (i=0;i>a[i][j];    //input the elements of array
    for (i=0;i


[wpedon id="7041" align="center"]

One thought on “C++ Program for Determinant of a Matrix using Gauss Elimination

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.