C program to find determinant of a matrix

Write a C program to read elements in a matrix and find determinant of the given matrix. C program to find determinant of a 2×2 matrix and 3×3 matrix. Logic to find determinant of a matrix in C programming.

Example

Input

Input elements in 2x2 matrix: 
1 2
3 4

Output

Determinant of the matrix = -2

Required knowledge

Basic C programming, For loop, Array

What is determinant?

The Determinant of a matrix is a special number that can be calculated from the elements of a square matrix. The determinant of a matrix A is denoted by det (A), det A or |A|.

Determinant of 2x2 matrix

Determinant of 3x3 matrix

Program to calculate determinant of 2×2 matrix

/**
 * C program to find determinant of 2x2 matrix
 */

#include <stdio.h>
#define SIZE 2 // Matrix size

int main()
{
    int A[SIZE][SIZE];
    int row, col;
    long det;

    /* Input elements in matrix A from user */
    printf("Enter elements in matrix of size 2x2: \n");
    for(row=0; row<SIZE; row++)
    {
        for(col=0; col<SIZE; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /*
     * det(A) = ad - bc
     * a = A[0][0], b = A[0][1], c = A[1][0], d = A[1][1]
     */
    det = (A[0][0] * A[1][1]) - (A[0][1] * A[1][0]);

    printf("Determinant of matrix A = %ld", det);

    return 0;
}

Output

Enter elements in matrix of size 2x2:
1 2
3 4
Determinant of matrix A = -2

Program to calculate determinant of 3×3 matrix

/**
 * C program to find determinant of 3x3 matrix
 */

#include <stdio.h>
#define SIZE 3 // Matrix size

int main()
{
    int A[SIZE][SIZE];
    int row, col;
    int a, b, c, d, e, f, g, h, i;
    long det;

    /* Input elements in matrix A from user */
    printf("Enter elements in matrix of size 3x3: \n");
    for(row=0; row<SIZE; row++)
    {
        for(col=0; col<SIZE; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /*
     * Used as a temporary variables to make calculation easy
     * |         |
     * | a  b  c |
     * | d  e  f |
     * | g  h  i |
     * |         |
     */
    a = A[0][0];
    b = A[0][1];
    c = A[0][2];
    d = A[1][0];
    e = A[1][1];
    f = A[1][2];
    g = A[2][0];
    h = A[2][1];
    i = A[2][2];

    /*
     * det(A) = a(ei - fh) - b(di - fg) + c(dh - eg)
     */
    det = (a*(e*i - f*h)) - (b*(d*i - f*g)) + (c*(d*h - e*g));

    printf("Determinant of matrix A = %ld", det);

    return 0;
}

Note: You can also calculate determinants without using additional temporary variables a, b, c, d, e, f, g, h, u. These variable are only used to make the program simple to use. You can directly use A[0][0] for a etc.

Output

Enter elements in matrix of size 3x3:
6 1 1
4 -2 5
2 8 7
Determinant of matrix A = -306

Happy coding 😉