Below is the program in C++ to find the determinant of matrix
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
typedef struct
{
int order;
int **ar; //for a 2-d array
}matrix;
int create( matrix *a,int order)
{
if(order<1)
return 0; //checks for invalid order
a->order=order;
a->ar= (int**) malloc(order*sizeof(int *)); //allocate space for each row
if(!a->ar)
return 0; //checks if memory is allocated
for(int i=0;i<order;i++)
{ a->ar[i]=(int*) malloc(order*sizeof(int));
if(!a->ar)
return 0;
}
return 1;
}
void input(matrix *a )
{
int i,j;
for( i = 0; i < a->order; i++ )
for( j = 0; j < a->order; j++ )
{
printf("Enter element at ( %d, %d ): ", i+1, j+1 );
scanf("%d", &a->ar[i][j] );
}
}
void display( matrix *a )
{
int i,j;
if( a->order < 1 )
return;
for( i = 0; i < a->order; i++ )
{
for( j = 0; j < a->order; j++ )
printf("%5d ", a->ar[i][j] );
printf("\n");
}
}
int calcminor(matrix *a, matrix *minor, int row,int column)
{
int p,q;
if(a->order<=1||row>=a->order||column>=a->order)
return 0;
if(!create(minor,a->order-1))
return 0;
p=q=0;
for(int i=0;i<a->order;i++)
if(i!=row)
{
q=0;
for(int j=0;j<a->order;j++)
{ if(j!=column)
minor->ar[p][q]=a->ar[i][j];
q++;
}
p++;
}
return 1;
}
void destroy(matrix *a)
{
if(a->order<1)
return;
for(int i=0;i<a->order;i++)
free(a->ar[i]); // free space for the column
free(a->ar); //free memory for rows
a->order=0;
}
int calcdet(matrix *a)
{
int result=0;
matrix minor;
if(a->order<1)
return 0;
if(a->order==1) // stopping condition
return a->ar[0][0]; //returns 0,0 element
for(int i=0;i<a->order;i++)
{
if(!calcminor(a,&minor,0,i))
return 0;
result+=( pow(-1,i)*a->ar[0][i]*calcdet(&minor));
destroy(&minor);
}
return result;
}
int main()
{
matrix a;
int order;
cout<<"\nEnter The Order of The Square Matrix :";
cin>>order;
if(!create(&a,order))
{
cout<<"\n The Matrix Could Not Be Created !!!! ";
getch();
return 0;
}
input(&a);
cout<<"The Matrix Is :\n";
display(&a);
cout<<"\n The Determinant Of The Matrix Is : "<<calcdet(&a);
getch();
return 0;
}