-
N by N Determinant
I am trying to make a program for n by n determinant. This program compiles correctly but it does not give a correct answer. I don't know why?
Code:
int Determinant(int m[DIM][DIM],int size);
int Cofactor(int m[DIM][DIM],int row,int col,int size);
int i,j,c,r;
void main()
{
int a[DIM][DIM] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int b[DIM][DIM] = {
{1, 2, 3, 4},
{4, 5, 7, 8},
{9, 0, 1, 2},
{3, 4, 5, 6},
};
printf("det a=%d\n",Determinant(a,3));
printf("det b=%d\n",Determinant(b,4));
}
int Determinant(int m[DIM][DIM], int size) {
if (size < 2) return 0;
if (size == 2) {
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
}
int d = 0;
for (i=0; i<size; i++)
d += m[0][i] * Cofactor(m, 0, i, size);
return d;
}
int Cofactor(int m[DIM][DIM], int row, int col, int size) {
int m2[DIM][DIM];
for (i=0,r=0; i<size; i++) {
if (i==row) continue;
for (j=0,c=0; j<size; j++) {
if (j==col) continue;
m2[r][c] = m[i][j];
c++;
}
r++;
}
return Determinant(m2,size-1) * (((row+col)%2==0)? 1 : (-1));
}
-
you have declared your loop counters as globals. so in your function Determinant, the 'i' in that loop gets modified when you use it in Cofactor. you should make your loop counters local to each function.
-
I'm guessing you just copy/pasted the code from here -> C programming problem? - Yahoo! Answers
Without really having a clue.
Because anyone smart enough to know what this might mean
> return Determinant(m2,size-1) * (((row+col)%2==0)? 1 : (-1));
would have no trouble figuring out why the code doesn't work.
Do yourself a favour and STOP COPYING OTHER PEOPLES crap code.
That is, if you're truly interested in learning how to program, and not just in some short-cut to passing the exam (no, it isn't a short cut - just wait until you get a job on the back of a scammed certificate).