C Online Compiler
Example: Determinant of N x N Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Determinant of N x N Matrix #include <stdio.h> #include <math.h> // For pow function // Function to get the cofactor of matrix[p][q] in temp matrix void getCofactor(int matrix[10][10], int temp[10][10], 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 elements which are not in given row and column if (row != p && col != q) { temp[i][j++] = matrix[row][col]; // Row is full, go to next row if (j == n - 1) { j = 0; i++; } } } } } // Function to calculate determinant of a matrix recursively int determinant(int matrix[10][10], int n) { int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) { return matrix[0][0]; } int temp[10][10]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of the first row for (int f = 0; f < n; f++) { // Getting Cofactor of matrix[0][f] getCofactor(matrix, temp, 0, f, n); D += sign * matrix[0][f] * determinant(temp, n - 1); // Term is multiplied by (-1)^(1+col_index) sign = -sign; } return D; } // Function to display the matrix void displayMatrix(int matrix[10][10], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } } int main() { // Step 1: Define an N x N matrix and its size int matrix1[10][10] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int n1 = 3; // Step 2: Calculate its determinant printf("Matrix 1 (%dx%d):\n", n1, n1); displayMatrix(matrix1, n1); printf("Determinant = %d\n", determinant(matrix1, n1)); printf("\n"); int matrix2[10][10] = { {1, 0, 2, -1}, {3, 0, 0, 5}, {2, 1, 4, -3}, {1, 0, 5, 0} }; int n2 = 4; printf("Matrix 2 (%dx%d):\n", n2, n2); displayMatrix(matrix2, n2); printf("Determinant = %d\n", determinant(matrix2, n2)); printf("\n"); int matrix3[10][10] = { {6, 1, 1}, {4, -2, 5}, {2, 8, 7} }; int n3 = 3; printf("Matrix 3 (%dx%d):\n", n3, n3); displayMatrix(matrix3, n3); printf("Determinant = %d\n", determinant(matrix3, n3)); return 0; }
Output
Clear
ADVERTISEMENTS