# matrix determinant

• 06-30-2009
roaan
matrix determinant
I am writing a program to calculate the determinant of an n*n matrix. The issue is that the program ends abruptly without giving any error and does not return the result of the determinant. I am using Visual Studio c++ 2008 for the same. The code for the calculation of the matrix determinant is as follows:

insert
Code:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int detmat(int *, int);

main(){

int* arr, i,j;
int result = 0, num, n=0, pos;

printf("\n\rEnter the order of matrix");
scanf("%d", &n);
arr = calloc(n*n, 2);

printf("Enter the elements");
for(i =0;i<n;i++){
for(j =0;j<n;j++){
scanf("%d", &num);
pos = i*n+j;
arr[pos] = num;
}
}

//print the matrix

for(i=0;i<n;i++){
for(j=i;j<n*n; j+= n){
printf("\t%d", arr[j]);
}
printf("\n\r");
}

result = detmat(arr, n);
free(arr);

printf("\n %d", result);

printf("\n\n\nPress any key to exit");
getch();

}

int detmat(int *arr, int order){

int *arr2, i,j,k, sign=1;
int pos, newpos, count, sum =0;

if(order == 1)
return (arr[0]);

for(i=0;i<order;i++, sign *= -1){

arr2 = calloc((order-1)*(order-1),2);

for(j=1;j<order;j++){
for(k=0,count =0;k < order;k++){

if(k == i)
continue;

pos = j*order+k;
newpos = (j-1)*(order-1) + count;
arr2[newpos] = arr[pos];
count++;
}

}

sum = sum + arr[i]*sign*detmat(arr2, order-1);
free(arr2);
}

return (sum);
}

• 06-30-2009
Salem
> arr = calloc(n*n, 2);
Try sizeof(int) rather than 2

But then you did just copy/paste this from some TurboC user from about 20 years ago.