Program to find Determinant of a Matrix

Last Updated : 23 Jul, 2025

The determinant of a Matrix is defined as a special number that is defined only for square matrices (matrices that have the same number of rows and columns). A determinant is used in 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.

Determinant of 2 x 2 Matrix:

1
determinant of 2 x 2 matrix

Determinant of 3 x 3 Matrix:

2
determinant of 3 x 3 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.
  • Then multiply the element with the determinant of the corresponding cofactor. 
  • 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. 

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

Try It Yourself
redirect icon
C++
#include <bits/stdc++.h>
using namespace std;

// Function for finding the determinant of a matrix.
int getDet(vector<vector<int>>& mat, int n) {
  
    // Base case: if the matrix is 1x1
    if (n == 1) {
        return mat[0][0];
    }
    
    // Base case for 2x2 matrix
    if (n == 2) {
        return mat[0][0] * mat[1][1] - 
               mat[0][1] * mat[1][0];
    }
    
    // Recursive case for larger matrices
    int res = 0;
    for (int col = 0; col < n; ++col) {
      
        // Create a submatrix by removing the first 
        // row and the current column
        vector<vector<int>> sub(n - 1, vector<int>(n - 1));
        for (int i = 1; i < n; ++i) {
            int subcol = 0;
            for (int j = 0; j < n; ++j) {
              
                // Skip the current column
                if (j == col) continue; 
              
                // Fill the submatrix
                sub[i - 1][subcol++] = mat[i][j]; 
            }
        }
      
        // Cofactor expansion
        int sign = (col % 2 == 0) ? 1 : -1; 
        res += sign * mat[0][col] * getDet(sub, n - 1);
    }
    
    return res; 
}

// Driver program to test the above function
int main() {
    vector<vector<int>> mat = { { 1, 0, 2, -1 },
                                 { 3, 0, 0, 5 },
                                 { 2, 1, 4, -3 },
                                 { 1, 0, 5, 0 } };
    cout << getDet(mat, mat.size()) << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

#define N 4 

// Function for finding the determinant of a matrix.
int getDet(int mat[N][N], int n) {
  
    // Base case: if the matrix is 1x1
    if (n == 1) {
        return mat[0][0];
    }
    
    // Base case for 2x2 matrix
    if (n == 2) {
        return mat[0][0] * mat[1][1] - 
               mat[0][1] * mat[1][0];
    }
    
    // Recursive case for larger matrices
    int res = 0;
    for (int col = 0; col < n; ++col) {
      
        // Create a submatrix by removing the 
        // first row and the current column
        int sub[N][N]; // Submatrix
        for (int i = 1; i < n; ++i) {
            int subcol = 0;
            for (int j = 0; j < n; ++j) {
              
                // Skip the current column
                if (j == col) continue; 
              
                // Fill the submatrix
                sub[i - 1][subcol++] = mat[i][j]; 
            }
        }
      
        // Cofactor expansion
        int sign = (col % 2 == 0) ? 1 : -1; 
        res += sign * mat[0][col] * getDet(sub, n - 1);
    }
    
    return res; 
}

// Driver program to test the above function
int main() {
    int mat[N][N] = { { 1, 0, 2, -1 },
                      { 3, 0, 0, 5 },
                      { 2, 1, 4, -3 },
                      { 1, 0, 5, 0 } };
    printf("%d\n", getDet(mat, N));
    return 0;
}
Java
// Function for finding the determinant of a matrix.
public class GfG {
    public static int getDet(int[][] mat, int n) {
      
        // Base case: if the matrix is 1x1
        if (n == 1) {
            return mat[0][0];
        }
        
        // Base case for 2x2 matrix
        if (n == 2) {
            return mat[0][0] * mat[1][1] - 
                   mat[0][1] * mat[1][0];
        }
        
        // Recursive case for larger matrices
        int res = 0;
        for (int col = 0; col < n; ++col) {
          
            // Create a submatrix by removing the first 
            // row and the current column
            int[][] sub = new int[n - 1][n - 1];
            for (int i = 1; i < n; ++i) {
                int subcol = 0;
                for (int j = 0; j < n; ++j) {
                  
                    // Skip the current column
                    if (j == col) continue; 
                    
                    // Fill the submatrix
                    sub[i - 1][subcol++] = mat[i][j]; 
                }
            }
            
            // Cofactor expansion
            int sign = (col % 2 == 0) ? 1 : -1; 
            res += sign * mat[0][col] * getDet(sub, n - 1);
        }
        
        return res; 
    }

    // Driver program to test the above function
    public static void main(String[] args) {
        int[][] mat = { { 1, 0, 2, -1 },
                         { 3, 0, 0, 5 },
                         { 2, 1, 4, -3 },
                         { 1, 0, 5, 0 } };
        System.out.println(getDet(mat, mat.length));
    }
}
Python
# Function for finding the determinant of a matrix.
def getDet(mat, n):
  
    # Base case: if the matrix is 1x1
    if n == 1:
        return mat[0][0]
    
    # Base case for 2x2 matrix
    if n == 2:
        return mat[0][0] * mat[1][1] - \
               mat[0][1] * mat[1][0]
    
    # Recursive case for larger matrices
    res = 0
    for col in range(n):
      
        # Create a submatrix by removing the first 
        # row and the current column
        sub = [[0] * (n - 1) for _ in range(n - 1)]
        for i in range(1, n):
            subcol = 0
            for j in range(n):
              
                # Skip the current column
                if j == col:
                    continue
                
                # Fill the submatrix
                sub[i - 1][subcol] = mat[i][j]
                subcol += 1
        
        # Cofactor expansion
        sign = 1 if col % 2 == 0 else -1
        res += sign * mat[0][col] * getDet(sub, n - 1)
    
    return res

# Driver program to test the above function
mat = [[1, 0, 2, -1],
       [3, 0, 0, 5],
       [2, 1, 4, -3],
       [1, 0, 5, 0]]
print(getDet(mat, len(mat)))
C#
// Function for finding the determinant of a matrix.
using System;
using System.Linq;

class Determinant {
    public static int GetDet(int[,] mat, int n) {
      
        // Base case: if the matrix is 1x1
        if (n == 1) {
            return mat[0, 0];
        }
        
        // Base case for 2x2 matrix
        if (n == 2) {
            return mat[0, 0] * mat[1, 1] - 
                   mat[0, 1] * mat[1, 0];
        }
        
        // Recursive case for larger matrices
        int res = 0;
        for (int col = 0; col < n; col++) {
          
            // Create a submatrix by removing the first 
            // row and the current column
            int[,] sub = new int[n - 1, n - 1];
            for (int i = 1; i < n; i++) {
                int subcol = 0;
                for (int j = 0; j < n; j++) {
                  
                    // Skip the current column
                    if (j == col) continue;
                    
                    // Fill the submatrix
                    sub[i - 1, subcol++] = mat[i, j];
                }
            }
            
            // Cofactor expansion
            int sign = (col % 2 == 0) ? 1 : -1;
            res += sign * mat[0, col] * GetDet(sub, n - 1);
        }
        
        return res;
    }

    // Driver program to test the above function
    static void Main() {
        int[,] mat = { { 1, 0, 2, -1 },
                        { 3, 0, 0, 5 },
                        { 2, 1, 4, -3 },
                        { 1, 0, 5, 0 } };
        Console.WriteLine(GetDet(mat, mat.GetLength(0)));
    }
}
JavaScript
// Function for finding the determinant of a matrix.
function getDet(mat, n) {

    // Base case: if the matrix is 1x1
    if (n === 1) {
        return mat[0][0];
    }
    
    // Base case for 2x2 matrix
    if (n === 2) {
        return mat[0][0] * mat[1][1] - 
               mat[0][1] * mat[1][0];
    }
    
    // Recursive case for larger matrices
    let res = 0;
    for (let col = 0; col < n; col++) {
    
        // Create a submatrix by removing the first 
        // row and the current column
        let sub = Array.from({ length: n - 1 }, () => new Array(n - 1));
        for (let i = 1; i < n; i++) {
            let subcol = 0;
            for (let j = 0; j < n; j++) {
            
                // Skip the current column
                if (j === col) continue;
                
                // Fill the submatrix
                sub[i - 1][subcol++] = mat[i][j];
            }
        }
        
        // Cofactor expansion
        let sign = (col % 2 === 0) ? 1 : -1;
        res += sign * mat[0][col] * getDet(sub, n - 1);
    }
    
    return res;
}

// Driver program to test the above function
let mat = [ [ 1, 0, 2, -1 ],
            [ 3, 0, 0, 5 ],
            [ 2, 1, 4, -3 ],
            [ 1, 0, 5, 0 ] ];
console.log(getDet(mat, mat.length));

Output
30

Time Complexity: O(n3)
Space Complexity: O(n2), Auxiliary space used for storing cofactors.

Note: In the above recursive approach when the size of the matrix is large it consumes more stack size.

Determinant of a Matrix using Determinant properties

We calculates the determinant of an N x N matrix using Gaussian elimination and a series of transformations that reduce the matrix to upper triangular form.

  • Converting the given matrix into an upper triangular matrix using determinant properties 
  • The determinant of the upper triangular matrix is the product of all diagonal elements. 
  • Iterating every diagonal element and making all the elements down the diagonal as zero using determinant properties 
  • If the diagonal element is zero then search for the 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 a matrix is zero 
  • Case 2: If there exists a non-zero element there exist two cases 
    • Case A: If the index is with a respective diagonal row element. Using the determinant properties make all the column elements down to it zero
    • Case B: Swap the row with respect to the diagonal element column and continue the Case A operation.
C++
#include <iostream>
#include <vector>
#include <cmath> // For pow function
using namespace std;

// Function to get determinant of a matrix
int getDet(vector<vector<int>>& mat) {
  
    int n = mat.size();
  
    int num1, num2, det = 1, index, total = 1; 
  
    // Temporary array for storing row
    vector<int> temp(n + 1); 

    // Loop for traversing the diagonal elements
    for (int i = 0; i < n; i++) {
        index = i; 

        // Finding the index which has non-zero value
        while (index < n && mat[index][i] == 0) {
            index++;
        }
      
        if (index == n) // If there is no non-zero element
        {
            continue; // The determinant of the matrix is zero
        }
        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
            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++) {
            num1 = temp[i]; // Value of diagonal element
            num2 = mat[j][i]; // Value of next row element

            // Traversing every column of row and
            // multiplying to every row
            for (int k = 0; k < n; k++) {
              
                // Making the diagonal element and next row element equal
                mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]);
            }
            total *= num1; 
        }
    }

    // Multiplying the diagonal elements to get determinant
    for (int i = 0; i < n; i++) {
        det *= mat[i][i];
    }
  
    return (det / total); // Det(kA)/k = Det(A);
}

// Driver code
int main() {
    vector<vector<int>> mat = {
        { 1, 0, 2, -1 },
        { 3, 0, 0, 5 },
        { 2, 1, 4, -3 },
        { 1, 0, 5, 0 }
    };
    cout << getDet(mat) << endl;
    return 0;
}
Java
import java.util.Arrays;

public class GfG {

    // Function to get the determinant of a matrix
    static int getDet(int[][] mat) {
        int n = mat.length;

        int num1, num2, det = 1, index, total = 1; 
      
        // Temporary array for storing row
        int[] temp = new int[n + 1];

        // Loop for traversing the diagonal elements
        for (int i = 0; i < n; i++) {
            index = i;

            // Finding the index which has a non-zero value
            while (index < n && mat[index][i] == 0) {
                index++;
            }
            if (index == n) { // If there is no non-zero element
                continue; // The determinant of the matrix is zero
            }
            if (index != i) {
              
                // Loop for swapping the diagonal element
                // row and index row
                for (int j = 0; j < n; j++) {
                    int tempSwap = mat[index][j];
                    mat[index][j] = mat[i][j];
                    mat[i][j] = tempSwap;
                }
                // Determinant sign changes when we shift rows
                det *= Math.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++) {
                num1 = temp[i]; // Value of diagonal element
                num2 = mat[j][i]; // Value of next row element

                // Traversing every column of row and multiplying
                // to every row
                for (int k = 0; k < n; k++) {
                  
                    // Making the diagonal element and next row 
                    // element equal
                    mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]);
                }
                total *= num1; 
            }
        }

        // Multiplying the diagonal elements to get determinant
        for (int i = 0; i < n; i++) {
            det *= mat[i][i];
        }

        return (det / total); // Det(kA)/k = Det(A);
    }

    // Driver code
    public static void main(String[] args) {
        int[][] mat = {
            { 1, 0, 2, -1 },
            { 3, 0, 0, 5 },
            { 2, 1, 4, -3 },
            { 1, 0, 5, 0 }
        };
        System.out.println(getDet(mat));
    }
}
Python
# Python program to find Determinant of a matrix
def getDet(mat):

    n  = len(mat)
    temp = [0]*n  # temporary array for storing row
    total = 1
    det = 1  # initialize result

    # loop for traversing the diagonal elements
    for i in range(0, n):
        index = i  # initialize the index

        # finding the index which has non zero value
        while(index < n and mat[index][i] == 0):
            index += 1

        if(index == n):  # if there is non zero element
            # the determinant of matrix as zero
            continue

        if(index != i):
          
            # loop for swapping the diagonal element 
            # row and index row
            for j in range(0, n):
                mat[index][j], mat[i][j] = mat[i][j], mat[index][j]

            # determinant sign changes when we shift rows
            # go through determinant properties
            det = det*int(pow(-1, index-i))

        # storing the values of diagonal row elements
        for j in range(0, n):
            temp[j] = mat[i][j]

        # traversing every row below the diagonal element
        for j in range(i+1, n):
            num1 = temp[i]     # value of diagonal element
            num2 = mat[j][i]   # value of next row element

            # traversing every column of row
            # and multiplying to every row
            for k in range(0, n):
              
                # 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 i in range(0, n):
        det = det*mat[i][i]

    return int(det/total)  # Det(kA)/k=Det(A);


# Drivers code
if __name__ == "__main__":
    # mat=[[6 1 1][4 -2 5][2 8 7]]

    mat = [[1, 0, 2, -1], [3, 0, 0, 5], [2, 1, 4, -3], [1, 0, 5, 0]]
   
    print(getDet(mat))
C#
using System;

class MatrixDeterminant
{
    // Function to get the determinant of a matrix
    static int getDet(int[,] mat)
    {
        int n = mat.GetLength(0);

        int num1, num2, det = 1, index, total = 1;
      
        // Temporary array for storing row
        int[] temp = new int[n + 1];

        // Loop for traversing the diagonal elements
        for (int i = 0; i < n; i++)
        {
            index = i;

            // Finding the index which has a non-zero value
            while (index < n && mat[index, i] == 0)
            {
                index++;
            }
          
             // If there is no non-zero element
            if (index == n)
            {
                // The determinant of the matrix is zero
                continue; 
            }
            if (index != i)
            {
                // Loop for swapping the diagonal element
                // row and index row
                for (int j = 0; j < n; j++)
                {
                    int tempSwap = mat[index, j];
                    mat[index, j] = mat[i, j];
                    mat[i, j] = tempSwap;
                }
              
                // Determinant sign changes when we shift rows
                det *= (int)Math.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++)
            {
                num1 = temp[i]; // Value of diagonal element
                num2 = mat[j, i]; // Value of next row element

                // Traversing every column of row and multiplying 
                // to every row
                for (int k = 0; k < n; k++)
                {
                    // Making the diagonal element and next row
                    // element equal
                    mat[j, k] = (num1 * mat[j, k]) - (num2 * temp[k]);
                }
                total *= num1;
            }
        }

        // Multiplying the diagonal elements to get determinant
        for (int i = 0; i < n; i++)
        {
            det *= mat[i, i];
        }

        return (det / total); // Det(kA)/k = Det(A);
    }

    // Driver code
    static void Main()
    {
        int[,] mat = {
            { 1, 0, 2, -1 },
            { 3, 0, 0, 5 },
            { 2, 1, 4, -3 },
            { 1, 0, 5, 0 }
        };
        Console.WriteLine(getDet(mat));
    }
}
JavaScript
// Function to get the determinant of a matrix
function determinantOfMatrix(mat) {
    const n = mat.length;
    let det = 1;
    let total = 1;

    // Temporary array for storing row
    const temp = new Array(n + 1).fill(0);

    // Loop for traversing the diagonal elements
    for (let i = 0; i < n; i++) {
        let index = i;

        // Finding the index which has a non-zero value
        while (index < n && mat[index][i] === 0) {
            index++;
        }
        if (index === n) {
            continue; // The determinant of the matrix is zero
        }
        if (index !== i) {
        
            // Swapping the diagonal element row and index row
            for (let j = 0; j < n; j++) {
                [mat[index][j], mat[i][j]] = [mat[i][j], mat[index][j]];
            }
            
            // Determinant sign changes when we shift rows
            det *= Math.pow(-1, index - i);
        }

        // Storing the values of diagonal row elements
        for (let j = 0; j < n; j++) {
            temp[j] = mat[i][j];
        }

        // Traversing every row below the diagonal element
        for (let j = i + 1; j < n; j++) {
            const num1 = temp[i]; // Value of diagonal element
            const num2 = mat[j][i]; // Value of next row element

            // Traversing every column of row and multiplying 
            // to every row
            for (let k = 0; k < n; k++) {
            
                // Making the diagonal element and next row 
                // element equal
                mat[j][k] = (num1 * mat[j][k]) - (num2 * temp[k]);
            }
            total *= num1; 
        }
    }

    // Multiplying the diagonal elements to get determinant
    for (let i = 0; i < n; i++) {
        det *= mat[i][i];
    }

    return (det / total); // Det(kA)/k = Det(A);
}

// Driver code
const mat = [
    [1, 0, 2, -1],
    [3, 0, 0, 5],
    [2, 1, 4, -3],
    [1, 0, 5, 0]
];
console.log(determinantOfMatrix(mat));

Output
30

Time complexity: O(n3
Auxiliary Space: O(n), Space used for storing row.

Determinant of a Matrix using NumPy package in Python

There is a built-in function or method in linalg module of NumPy package in python. It can be called numpy.linalg.det(mat) which returns the determinant value of the matrix mat passed in the argument.


Comment