Reputation: 21
I cannot understand why this program is producing wrong determinant values for matrices. This program uses the recursive calls to the function func() which converts the argument matrix to its minor which is then ultimately reduced to a single element. Please help, What is the error in this code..??
#include<stdio.h>
#include<math.h>
void display_(int arr[][4])
{
int i,j;
putchar('\n');
for(i=0;i<4;i++)
{for(j=0;j<4;j++)
printf("%d\t",arr[i][j]);
printf("\n");
}
}
int func(int arr[][4],int i,int j,int order)
{
if(order==1)
return arr[0][0];
return(pow(-1,i+j)*arr[i][j]*func(arr,i+1,j+1,order-1));
}
int main()
{
int i,j,matrix[4][4];
printf("\nEnter the elements to the matrix : ");
for(i=0;i<4;i++)
for(j=0;j<4;j++)
scanf("%d",&matrix[i][j]);
display_(matrix);
printf("\nDeterminant : %d",func(matrix,0,0,4));
}
Upvotes: 1
Views: 11552
Reputation: 68140
That is not the correct formula. See here.
Do you want to implement the Laplace formula? In that case, you need a sum over all rows and then recursively calculate the minors. That are the determinants of the matrix that results from A by removing the i-th row and the j-th column. That is where you use your function recursively.
Or do you want to implement the Leibniz formula? In that case, you need a sum and iterate over all possible permutations and then a product where you iterate over the number of rows (or columns). But you don't need recursion there.
Note that there are quite a few similar questions here on SO, e.g. here or here.
Upvotes: 2