0
0
CProgramBeginner · 2 min read

C Program to Find Determinant of Matrix

A C program to find the determinant of a matrix uses a recursive function that calculates the determinant by expanding along the first row with determinant() and getCofactor() functions.
📋

Examples

InputMatrix: [[5]]
OutputDeterminant: 5
InputMatrix: [[1, 2], [3, 4]]
OutputDeterminant: -2
InputMatrix: [[6, 1, 1], [4, -2, 5], [2, 8, 7]]
OutputDeterminant: -306
🧠

How to Think About It

To find the determinant of a matrix, think of it as breaking down the matrix into smaller parts called cofactors. For a 1x1 matrix, the determinant is the single element. For larger matrices, pick a row (usually the first), and for each element, calculate the determinant of the smaller matrix left when you remove that element's row and column. Multiply each element by its cofactor and add them up to get the determinant.
📐

Algorithm

1
Get the size of the square matrix.
2
If the matrix size is 1, return the single element as the determinant.
3
For each element in the first row, find its cofactor matrix by removing its row and column.
4
Recursively calculate the determinant of each cofactor matrix.
5
Multiply each element by its cofactor determinant and the sign (+ or -) based on position.
6
Sum all these values to get the determinant of the original matrix.
💻

Code

c
#include <stdio.h>

void getCofactor(int mat[10][10], int temp[10][10], int p, int q, int n) {
    int i = 0, j = 0;
    for (int row = 0; row < n; row++) {
        for (int col = 0; col < n; col++) {
            if (row != p && col != q) {
                temp[i][j++] = mat[row][col];
                if (j == n - 1) {
                    j = 0;
                    i++;
                }
            }
        }
    }
}

int determinant(int mat[10][10], int n) {
    if (n == 1) return mat[0][0];
    int det = 0, temp[10][10];
    int sign = 1;
    for (int f = 0; f < n; f++) {
        getCofactor(mat, temp, 0, f, n);
        det += sign * mat[0][f] * determinant(temp, n - 1);
        sign = -sign;
    }
    return det;
}

int main() {
    int n = 3;
    int mat[10][10] = {
        {6, 1, 1},
        {4, -2, 5},
        {2, 8, 7}
    };
    printf("Determinant: %d\n", determinant(mat, n));
    return 0;
}
Output
Determinant: -306
🔍

Dry Run

Let's trace the determinant calculation for the 3x3 matrix [[6,1,1],[4,-2,5],[2,8,7]] through the code.

1

Start determinant calculation

Matrix size n=3, start expanding along first row elements: 6, 1, 1.

2

Calculate cofactor for element 6 (position 0,0)

Remove row 0 and column 0, cofactor matrix is [[-2,5],[8,7]].

3

Calculate determinant of cofactor [[-2,5],[8,7]]

det = (-2*7) - (5*8) = -14 - 40 = -54.

4

Calculate cofactor for element 1 (position 0,1)

Remove row 0 and column 1, cofactor matrix is [[4,5],[2,7]].

5

Calculate determinant of cofactor [[4,5],[2,7]]

det = (4*7) - (5*2) = 28 - 10 = 18.

6

Calculate cofactor for element 1 (position 0,2)

Remove row 0 and column 2, cofactor matrix is [[4,-2],[2,8]].

7

Calculate determinant of cofactor [[4,-2],[2,8]]

det = (4*8) - (-2*2) = 32 + 4 = 36.

8

Combine results with signs

determinant = 6*(-54) - 1*(18) + 1*(36) = -324 - 18 + 36 = -306.

ElementCofactor DeterminantSignContribution
6-54+-324
118--18
136+36
💡

Why This Works

Step 1: Base case for recursion

When the matrix size is 1, the determinant is just the single element, so return it directly.

Step 2: Finding cofactors

For each element in the first row, create a smaller matrix by removing that element's row and column to find its cofactor.

Step 3: Recursive determinant calculation

Calculate the determinant of each cofactor matrix recursively, multiplying by the element and the sign (+ or -) based on position.

Step 4: Summing contributions

Add all these signed products together to get the determinant of the original matrix.

🔄

Alternative Approaches

Using Gaussian elimination
c
#include <stdio.h>

int determinant(int mat[10][10], int n) {
    int det = 1;
    for (int i = 0; i < n; i++) {
        int pivot = i;
        while (pivot < n && mat[pivot][i] == 0) pivot++;
        if (pivot == n) return 0;
        if (pivot != i) {
            for (int j = 0; j < n; j++) {
                int temp = mat[i][j];
                mat[i][j] = mat[pivot][j];
                mat[pivot][j] = temp;
            }
            det = -det;
        }
        det *= mat[i][i];
        for (int k = i + 1; k < n; k++) {
            int factor = mat[k][i] / mat[i][i];
            for (int j = i; j < n; j++) {
                mat[k][j] -= factor * mat[i][j];
            }
        }
    }
    return det;
}

int main() {
    int n = 3;
    int mat[10][10] = {
        {6, 1, 1},
        {4, -2, 5},
        {2, 8, 7}
    };
    printf("Determinant: %d\n", determinant(mat, n));
    return 0;
}
This method is faster for large matrices but modifies the original matrix and is more complex to implement.
Hardcoded formula for 2x2 matrix
c
#include <stdio.h>

int determinant2x2(int mat[2][2]) {
    return mat[0][0]*mat[1][1] - mat[0][1]*mat[1][0];
}

int main() {
    int mat[2][2] = {{1, 2}, {3, 4}};
    printf("Determinant: %d\n", determinant2x2(mat));
    return 0;
}
This is simple and efficient but only works for 2x2 matrices.

Complexity: O(n!) time, O(n^2) space

Time Complexity

The recursive method expands cofactors for each element, leading to factorial time complexity because each step reduces matrix size by one but calls multiple recursive calls.

Space Complexity

Extra space is used for temporary cofactor matrices of size (n-1)x(n-1) at each recursion level, leading to O(n^2) space.

Which Approach is Fastest?

Gaussian elimination is faster (O(n^3)) for large matrices, while recursion is simpler but slow for big sizes.

ApproachTimeSpaceBest For
Recursive Cofactor ExpansionO(n!)O(n^2)Small matrices (n <= 5)
Gaussian EliminationO(n^3)O(1)Large matrices
Hardcoded 2x2 FormulaO(1)O(1)2x2 matrices only
💡
Use recursion for small matrices and Gaussian elimination for larger ones to find determinants efficiently.
⚠️
Beginners often forget to alternate the sign (+/-) when expanding cofactors, leading to wrong results.