Reputation: 41
I want to correct this code to calculate determinant of a nxn matrix. The code below is what I have done so far. but it's giving the right answer up to 3x3 matrices and greater than that it is giving wrong value. I've also checked the part separately where minor matrices are formed from the main matrix and it is working perfectly. Still I don't know why it is returning wrong value for 4x4 and greater matrices?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
int dete(int, int (*)[]);
int main()
{
int a[3][3]=
{
1,4,3,
2,1,5,
3,2,1
};
int b[4][4]=
{
5,3,-2,-6,
1,2,7,4,
-10,3,5,-3,
-4,2,6,1
};
int ans1,ans2;
ans1=dete(3,a);//ans1 = 46 and this is correct
ans2=dete(4,b);//ans2 = 174 but it is giving 5169 which is wrong
printf("%d, %d", ans1, ans2);
getch();
}
int dete(int row, int arr[][row])
{
int col_main_mark,col_main,row_main,col_minor,cof,x,y;
int minor[row-1][row-1];
static int det=0;
if(row==2)//condition to stop recursion
{
det = arr[0][0] * arr[1][1] - arr[0][1] * arr[1][0];
return det;
}
for(col_main_mark=0; col_main_mark<row; col_main_mark++)//for specific col value of main matrix (arr[row][row])
{
cof=arr[0][col_main_mark];
//following two loop will make the minor matrix (minor[row-1][row-1]) from the main marix
for(row_main=0; row_main<row; row_main++)
{
for(col_main=0,col_minor=0; col_main<row; col_main++)
{
if(col_main==col_main_mark)
continue;
minor[row_main][col_minor]=arr[row_main+1][col_main]; col_minor++;
}
}
det = det + cof * pow(-1,col_main_mark) * dete(row-1, minor);
}
return det;
}
Upvotes: 3
Views: 670
Reputation: 31366
The solution is to remove static
. The variable det
will only be zero the first time the function is run. The next time it will have have the same value as it had in the end of the last call.
You can try with a two or more 3x3 matrices in a row. Only the first call to dete
will yield the correct result.
Upvotes: 3