#include #define N 100 float determinant(); void copy_matrix(); void add_row(float *, float *, float, int); int find_nonzero_row(); void read_matrix(); /* Computes the determinant of size n matrix * stored in array A using recursion. */ float determinant(float A[][N], int n) { int i; float B[N][N]; // stores a submatrix of A if (n == 1) // 1 x 1 matrix return A[0][0]; if (A[0][0] == 0) { i = find_nonzero_row(A, n); if (i >= n) // no non-zero row return 0; // determinant is 0 add_row(A[0], A[i], 1, n); // add row #i to row #0 } for (int t = 1; t < n; t++) // make first column of A[t] zero add_row(A[t], A[0], -A[t][0] / A[0][0], n); // Drop the first row and column of A copy_matrix(B, A, 1, n-1); /* The determinant of A equals the determinant of B times * A[0][0]. */ return A[0][0] * determinant(B, n-1); } /* Returns the first row of B whose first element is non-zero */ int find_nonzero_row(float B[][N], int m) { int i; for (i = 0; i < m; i++) if (B[i][0] != 0.0) return i; return i; } /* Copies matrix B to A by dropping the first i rows and columns of * A first. The size of matrix B is m. */ void copy_matrix(float A[][N], float B[][N], int i, int m) { int j, k; for (k = 0; k < m; k++) for (j = 0; j < m; j++) A[k][j] = B[k+i][j+i]; } /* Adds row_2 to row_1 by first multiplying it with factor. The * size of rows is m. */ void add_row(float *row_1, float *row_2, float factor, int m) { for (int i = 0; i < m; i++) row_1[i] = row_1[i] + factor * row_2[i]; } int main() { int n; float A[N][N]; read_matrix(A, &n); printf("Determinant of the matrix = %f\n", determinant(A, n)); } void read_matrix(float A[][N], int *ptr_n) { printf("Input the size of the matrix: "); scanf("%d", ptr_n); printf("Input the %d x %d matrix:\n", *ptr_n, *ptr_n); for (int i = 0; i < *ptr_n; i++) for (int j = 0; j < *ptr_n; j++) scanf("%f", &A[i][j]); }