The code below calculates the determinant of a matrix of order q recursively. It works for q=3 and q=2 but for q=4 it outputs garbage values which change every time I run the program: What is going wrong here?
#include <stdio.h>
#include <math.h>
int det(int q, int arr[q][q]);
int main(void)
{
int arr[4][4] = {
{2,4,9,8},
{6,3,4,5},
{5,7,8,6},
{3,2,5,7}
};
printf("value of determinant is %d\n", det(4, arr));
}
int det(int q, int arr[q][q])
{
if(q>2)
{
int i, j, k, m, n, s[q-1][q-1], d=0, cof;
for(k=-1,i=0,j=0;k<q-1;k++)
{
i=0;j=0;
for(m=1;m<q;m++,i++)
{
n=0;j=0;
for(n,j;n<k+1;n++,j++)
{
s[i][j] = arr[m][n];
}
n=q-1+k;
for(n;n<q;n++,j++)
{
s[i][j] = (arr[m][n]);
}
}
cof = (arr[0][k+1])*(pow(-1,k+1));
d += cof*det(q-1, s);
}
return d;
}
else if(q==2)
{
int d = ((arr[0][0])*(arr[1][1])-(arr[0][1])*(arr[1][0]));
return d;
}
}