Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
C Program To Find Normal and Trace of Matrix
Next article icon

C Program to Find Determinant of a Matrix

Last Updated : 15 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

[Tex]A = egin{bmatrix} a & b\ c & d end{bmatrix} egin{vmatrix} A end{vmatrix}= ad – bc                    [/Tex]

22

Determinant of 3 x 3 Matrix: 
[Tex]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)                      [/Tex] 

Recommended PracticeCost of SweetsTry It!

C

// C program to find Determinant
// of a matrix
#include <stdio.h>
 
// 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 the
   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++)
            printf("  %d", mat[i][j]);
        printf("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
    printf("Determinant of the matrix is : %d",
            determinantOfMatrix(mat, N));
    return 0;
}
                      
                       

Output
Determinant of the matrix is : 30

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

Efficient Approach:

Determinant of a Matrix using Determinant properties:

  • In this method, we are using the properties of Determinant. 
  • 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.

Below is the implementation of the above approach:

C++

// C program to find Determinant of a matrix
 
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
 
// Dimension of input square matrix
#define N 4
 
// This function swaps values pointed by xp and yp
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
 
// Function to get determinant of matrix
int determinantOfMatrix(int mat[N][N], int n)
{
    int num1, num2, det = 1, index,
                    total = 1; // Initialize result
 
    // temporary array for storing row
    int temp[n + 1];
 
    // loop for traversing the diagonal elements
    for (int i = 0; i < n; i++)
    {
        index = i; // initialize the index
 
        // finding the index which has non zero value
        while (index < n && mat[index][i] == 0)
        {
            index++;
        }
        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 (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++)
        {
            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++)
            {
                // 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];
    }
   
    return (det / total); // Det(kA)/k=Det(A);
}
 
// Driver code
int main()
{
    /*int mat[N][N] = {{6, 1, 1},
                        {4, -2, 5},
                        {2, 8, 7}}; */
 
    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(N*N*N), where N is the size of the matrix

Space Complexity: O(N) as temp array has been created to store row.

For more details, refer to the article – Determinant of a Matrix



Next Article
C Program To Find Normal and Trace of Matrix
author
kartik
Improve
Article Tags :
  • C Language
  • C Programs
  • C Array Programs

Similar Reads

  • C Program To Find Normal and Trace of Matrix
    Here, we will see how to write a C program to find the normal and trace of a matrix. Below are the examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};Output: Normal = 16Trace = 15 Explanation: Normal = sqrt(1*1+ 2*2 + 3*3 + 4*4 + 5*5 + 6*6 + 7*7 + 8*8 + 9*9) = 16Trace = 1+5+9 = 15 Input: m
    2 min read
  • C Program to Print Boundary Elements of a Matrix
    Here, we will print the boundary elements of a matrix using a C program: Input : 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output : 1 2 3 4 1 4 1 4 1 2 3 4Approach:Traverse the matrix from start to end.Assign an outer loop to point to the row and the inner row to traverse the elements of the row.if the elemen
    2 min read
  • C Program for Identity Matrix
    Introduction to Identity Matrix : The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1's and all other elements are zeros. In the below image, every matrix is an Identity Matrix. In linear algebra, this is sometimes call
    2 min read
  • C Program to Interchange Elements of First and Last in a Matrix Across Rows
    Here, we will see how to interchange the elements of first and last in a matrix across rows. Below are the examples: Input: 6 3 1 4 5 2 2 4 9Output: 2 4 9 4 5 2 6 3 1 Input: 1 3 5 4 5 2 2 2 4 Output: 2 2 4 4 5 2 1 3 5 Approach: The approach is very simple, swap the elements of the first and last row
    2 min read
  • C Program to Interchange Elements of First and Last in a Matrix Across Columns
    Here, we will see how to interchange the elements of the first and last element/entries in a matrix across columns; with an approach of swapping. Input: 9 7 5 2 3 4 5 2 6 Output: 5 7 9 4 3 2 6 2 5Approach: Swapping The approach is very simple for this program, we can simply swap the elements of the
    2 min read
  • C Program to Interchange Two Random Rows in a Matrix
    In this article, we will write a C program to interchange two random rows in a matrix. Below are the inputs that will be taken from the user: The number of rows & columns in the matrixThe elements in the matrixThe rows that will be interchanged Examples: Input: rows = 3, columns = 3 arr[i, j] =
    2 min read
  • C Program for Kronecker Product of two matrices
    Given a [Tex]{m} imes{n} [/Tex]matrix A and a [Tex]{p} imes{q} [/Tex]matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is an [Tex]{(mp)} imes{(nq)} [/Tex]matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22
    3 min read
  • C Program for Find the number of islands | Set 1 (Using DFS)
    Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands Example: Input: mat[][] = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1} Output: 5This is a variation of the standard
    3 min read
  • C Program to Check Whether Two Matrices Are Equal or Not
    Here, we will see how to check whether two matrices are equal or not using a C Program Input: First Matrix: 1, 2, 3, 4 1, 2, 3, 4 1, 2, 3, 4 1, 2, 3, 4 Second matrix: 1, 2, 3, 4 1, 2, 3, 4 1, 2, 3, 4 1, 2, 3, 4 Output: Matrices are equal.Approach: For any two matrices to be equal, the number of rows
    2 min read
  • Sort Matrix in alternating ascending and descending order rowwise
    Given an N x N matrix, our task is to print the row of the matrix in ascending and descending order alternatively.Examples: Input: 5 7 3 4 9 5 8 2 6 3 8 1 5 8 9 3 Output: 3 4 5 7 9 8 5 2 1 3 6 8 9 8 5 3 Explanation: Here the first row is sorted in ascending order, second row sorted in descending ord
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences