#include<iostream.h>
#include<conio.h>
#include<math.h>
double Det (double a[2][2], int size);
void form(double a[2][2], int c, int size);
double b[2][2];
double Det(double a[2][2], int size) {
if (size==1) {
return a[0][0];
}
else {
double ans = 0.0;
int c;
for (c=0;c<size;c++) {
form(a,c,size);
ans += pow(-1.0,(double)c)*Det(b,size-1);
}
return ans;
}
}
void form(double a[2][2], int c, int size) {
int i,j=0,k,l=0;
for (i=0;i<size;i++) {
for (j=0;j<size;j++) {
if ((i!=0)&&(j!=c)) {
if (l==size-1) {
k++;
l=0;
}
b[k][l]=a[i][j];
l++;
}
}
}
}
int main() {
double mat[2][2] = {{1.0,2.0},{3.0,7.0}};
cout << Det(mat,2);
getch();
return 0 ;
}
I am writing a program in C++ to calculate the determinant of a matrix using recursion. I know that there are many better algorithms to do the same. However, I have been asked to implement this one. As a test case, I have used the matrix specified in the code. When I this run this code, I get an answer of -4 instead of 1. I do not understand what is wrong with this code. Could someone please help? Thanks in advance.