C++ Program to Find the Determinant of a Matrix

Calculating the determinant of a matrix can be a bit complex, especially for matrices larger than 2×2. Below is a C++ program to find the determinant of a square matrix using the recursive method of expansion by minors for any square matrix:

#include <iostream>

#include <cmath>

using namespace std;

const int MAX_SIZE = 100;

void getCofactor(int mat[MAX_SIZE][MAX_SIZE], int temp[MAX_SIZE][MAX_SIZE], 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 determinantOfMatrix(int mat[MAX_SIZE][MAX_SIZE], int n) {

    int D = 0;

    if (n == 1) {

        return mat[0][0];

    }

    int temp[MAX_SIZE][MAX_SIZE];

    int sign = 1;

    for (int f = 0; f < n; f++) {

        getCofactor(mat, temp, 0, f, n);

        D += sign * mat[0][f] * determinantOfMatrix(temp, n – 1);

        sign = -sign;

    }

    return D;

}

int main() {

    int n;

    cout << “Enter the size of the square matrix: “;

    cin >> n;

    int mat[MAX_SIZE][MAX_SIZE];

    cout << “Enter the elements of the square matrix:\n”;

    for (int i = 0; i < n; ++i) {

        for (int j = 0; j < n; ++j) {

            cin >> mat[i][j];

        }

    }

    cout << “Determinant of the matrix: ” << determinantOfMatrix(mat, n) << endl;

    return 0;

}

Explanation:

  1. ‘getCofactor’ function calculates the cofactor matrix for a given element of the matrix.
  2. determinantOfMatrix function calculates the determinant of the matrix recursively using the expansion by minors method.
  3. In the main’ function, it takes input for the size of the square matrix and its elements. Then it calls the ‘determinantOfMatrix’ function to calculate the determinant and prints the result.

Leave a Reply

error: Content is protected !!