#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 * strored in array A. */ float determinant(float A[][N], int n) { float B[N][N]; // stores a submatrix of A int m; // the size of submatrix B int i; float det = 1.0; // stores the determinant of matrix A copy_matrix(B, A, 0, n); // copy matrix A to B for (m = n; m > 0; m--) { if (B[0][0] == 0) { i = find_nonzero_row(B, m); if (i >= m) // no non-zero row return 0; // determinant is 0 add_row(B[0], B[i], 1, m); // add row #i to row #0 } for (int t = 1; t < m; t++) // make first column of B[t] zero add_row(B[t], B[0], -B[t][0] / B[0][0], m); det = det * B[0][0]; // update determinant value // Drop the first row and column of B copy_matrix(B, B, 1, m-1); } // return the product of diagonal elements return det; } /* 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]); }