Determinant of a Matrix in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to find the determinant of a matrix.

Let's see the steps to find the determinant of a matrix.

  • Initialize the matrix.

  • Write a function to find the determinant of the matrix.

    • If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing.

    • Initialize variables for determinant, submatrix, sign.

    • Iterate from 1 to the size of the matrix N.

    • Find the submatrix for the current matrix element.

      • All the elements that are not in the current element row and column

    • Add the product of the current element and its cofactor to the determinant.

    • Alter the sign.

  • Print the determinant of the matrix.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define N 3
void subMatrix(int mat[N][N], int temp[N][N], int p, int q, int n) {
   int i = 0, j = 0;
   // filling the sub matrix
   for (int row = 0; row < n; row++) {
      for (int col = 0; col < n; col++) {
         // skipping if the current row or column is not equal to the current
         // element row and column
         if (row != p && col != q) {
            temp[i][j++] = mat[row][col];
            if (j == n - 1) {
               j = 0;
               i++;
            }
         }
      }
   }
}
int determinantOfMatrix(int matrix[N][N], int n) {
   int determinant = 0;
   if (n == 1) {
      return matrix[0][0];
   }
   if (n == 2) {
      return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
   }
   int temp[N][N], sign = 1;
   for (int i = 0; i < n; i++) {
      subMatrix(matrix, temp, 0, i, n);
      determinant += sign * matrix[0][i] * determinantOfMatrix(temp, n - 1);
      sign = -sign;
   }
   return determinant;
}
int main() {
   int mat[N][N] = {{2, 1, 3}, {6, 5, 7}, {4, 9, 8}};
   cout << "Determinant: " << determinantOfMatrix(mat, N) << endl;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

Determinant: 36

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 27-Jan-2021 12:27:23
Advertisements