Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ Program For Determinant of a Matrix

Improve Article
Save Article
Like Article
  • Last Updated : 05 Mar, 2023
Improve Article
Save Article
Like Article

What is the Determinant of a Matrix? 
The determinant of a Matrix is a special number that is defined only for square matrices (matrices that have the same number of rows and columns). A determinant is used at many places in calculus and other matrices related to algebra, it actually represents the matrix in terms of a real number which can be used in solving a system of a linear equation and finding the inverse of a matrix.

How to calculate? 
The value of the determinant of a matrix can be calculated by the following procedure – 
For each element of the first row or first column get the cofactor of those elements and then multiply the element with the determinant of the corresponding cofactor, and finally add them with alternate signs. As a base case, the value of the determinant of a 1*1 matrix is the single value itself. 

Cofactor of an element is a matrix that we can get by removing the row and column of that element from that matrix.

Determinant of 2 x 2 Matrix:

A = egin{bmatrix} a & b\ c & d end{bmatrix} egin{vmatrix} A end{vmatrix}= ad - bc
 

22

Determinant of 3 x 3 Matrix: 
A = egin{bmatrix} a & b & c\ d & e & f\ g & h & i end{bmatrix} egin{vmatrix} A end{vmatrix}= a(ei-fh)-b(di-gf)+c(dh-eg)                       

C++




// C++ program to find Determinant
// of a matrix
#include <iostream>
using namespace std;
 
// Dimension of input square matrix
#define N 4
 
// Function to get cofactor of
// mat[p][q] in temp[][]. n is
// current dimension of mat[][]
void getCofactor(int mat[N][N],
                 int temp[N][N], int p,
                 int q, int n)
{
    int i = 0, j = 0;
 
    // Looping for each element of
    // the matrix
    for (int row = 0; row < n; row++)
    {
        for (int col = 0; col < n; col++)
        {
            // Copying into temporary matrix
            // only those element which are
            // not in given row and column
            if (row != p && col != q)
            {
                temp[i][j++] = mat[row][col];
 
                // Row is filled, so increase row
                // index and reset col index
                if (j == n - 1)
                {
                    j = 0;
                    i++;
                }
            }
        }
    }
}
 
/* Recursive function for finding
   determinant of matrix.
   n is current dimension of mat[][]. */
int determinantOfMatrix(int mat[N][N], int n)
{
    // Initialize result
    int D = 0;
 
    //  Base case : if matrix contains
    // single element
    if (n == 1)
        return mat[0][0];
 
    // To store cofactors
    int temp[N][N];
 
    // To store sign multiplier
    int sign = 1;
 
    // Iterate for each element of
    // first row
    for (int f = 0; f < n; f++)
    {
        // Getting Cofactor of mat[0][f]
        getCofactor(mat, temp, 0, f, n);
        D += sign * mat[0][f] *
             determinantOfMatrix(temp, n - 1);
 
        // terms are to be added with alternate sign
        sign = -sign;
    }
 
    return D;
}
 
// Function for displaying the matrix
void display(int mat[N][N],
             int row, int col)
{
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
            cout << "  " <<  mat[i][j];
        cout << "n";
    }
}
 
// Driver code
int main()
{
    int mat[N][N] = {{1, 0, 2, -1},
                     {3, 0, 0, 5},
                     {2, 1, 4, -3},
                     {1, 0, 5, 0}};
 
    // Function call
    cout << "Determinant of the matrix is : " <<
             determinantOfMatrix(mat, N);
    return 0;
}
 
// This code is contributed by shivanisinghss2110


Output

Determinant of the matrix is : 30

Time Complexity: O(n!).

Explanation: The time complexity of the getCofactor() function is O(N^2) as it involves looping through all the elements of an N x N matrix. The time complexity of the determinantOfMatrix() function can be calculated using the following recurrence relation:

T(N) = N*T(N-1) + O(N^3)

The first term N*T(N-1) represents the time taken to calculate the determinant of the (N-1) x (N-1) submatrices, and the second term O(N^3) represents the time taken to calculate the cofactors for each element in the first row of the original matrix. Using expansion by minors, we can calculate the determinant of an NxN matrix as a sum of determinants of (N-1)x(N-1) matrices, each of which requires O(N^2) operations to calculate the cofactors. Therefore, the time complexity of the determinantOfMatrix() function is O(N!), which is the worst-case scenario where the matrix is a permutation matrix.

The display() function has a time complexity of O(N^2) as it loops through all the elements of the matrix to print them. The overall time complexity of the program is dominated by the determinantOfMatrix() function, so the time complexity of the program is O(N!).

Space Complexity: O(n*n) as temp matrix has been created.

Adjoint and Inverse of a Matrix 
There are various properties of the Determinant which can be helpful for solving problems related with matrices, 
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

In Above Method Recursive Approach is discussed. When the size of matrix is large it consumes more stack size 
In this Method We are using the properties of Determinant. In this approach we are converting the given matrix into upper triangular matrix using determinant properties The determinant of upper triangular matrix is the product of all diagonal elements For properties on determinant go through this website https://cran.r-project.org/web/packages/matlib/vignettes/det-ex1.html 

In this approach, we are iterating every diagonal element and making all the elements down the diagonal as zero using determinant properties 

If the diagonal element is zero then we will search next non zero element in the same column 

There exist two cases 
Case 1: 
If there is no non-zero element. In this case the determinant of matrix is zero 
Case 2: 
If there exists non-zero element there exist two cases 
Case a: 
if index is with respective diagonal row element. Using the determinant properties we make all the column elements down to it as zero 
Case b: 
Here we need to swap the row with respective to diagonal element column and continue the case ‘a; operation 

Below is the implementation of the above approach:

C++




// C++ program to find Determinant
// of a matrix
#include <bits/stdc++.h>
using namespace std;
 
// Dimension of input square matrix
#define N 4
 
// Function to get determinant of matrix
int determinantOfMatrix(int mat[N][N], int n)
{
    // Initialize result
    int num1, num2, det = 1, index,
                    total = 1;
 
    // Temporary array for storing row
    int temp[n + 1];
 
    // Loop for traversing the diagonal elements
    for (int i = 0; i < n; i++)
    {
        // Initialize the index
        index = i;
 
        // Finding the index which has
        // non zero value
        while (index < n && mat[index][i] == 0)
        {
            index++;
        }
 
        // if there is non zero element
        if (index == n)
        {
            // the determinant of matrix
            // as zero
            continue;
        }
        if (index != i)
        {
            // Loop for swapping the diagonal
            // element row and index row
            for (int j = 0; j < n; j++)
            {
                swap(mat[index][j], mat[i][j]);
            }
 
            // Determinant sign changes when we
            // shift rows go through determinant
            // properties
            det = det * pow(-1, index - i);
        }
 
        // Storing the values of diagonal
        // row elements
        for (int j = 0; j < n; j++)
        {
            temp[j] = mat[i][j];
        }
 
        // Traversing every row below the
        // diagonal element
        for (int j = i + 1; j < n; j++)
        {
            // Value of diagonal element
            num1 = temp[i];
 
            // Value of next row element
            num2 = mat[j][i];
 
            // Traversing every column of row
            // and multiplying to every row
            for (int k = 0; k < n; k++)
            {
                // Multiplying to make the diagonal
                // element and next row element equal
                mat[j][k]
                    = (num1 * mat[j][k]) - (num2 * temp[k]);
            }
            total = total * num1; // Det(kA)=kDet(A);
        }
    }
 
    // Multiplying the diagonal elements to
    // get determinant
    for (int i = 0; i < n; i++)
    {
        det = det * mat[i][i];
    }
 
    // Det(kA)/k=Det(A);
    return (det / total);
}
 
// Driver code
int main()
{
    int mat[N][N] = {{1, 0, 2, -1},
                     {3, 0, 0, 5},
                     {2, 1, 4, -3},
                     {1, 0, 5, 0}};
 
    // Function call
    printf("Determinant of the matrix is : %d",
            determinantOfMatrix(mat, N));
    return 0;
}


Output:

Determinant of the matrix is : 30

Time complexity: O(n3
Auxiliary Space: O(n) 
 


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!