Saturday, July 7, 2012

Determinant Calculator

C-program to calculate the determinant of a square matrix of any dimensions up to [100x100]

#include<stdio.h>
int main()
{
int determinant(int A[][100],int n,int i,int s);
int A[100][100],i,n,B[100];
printf("Enter the number of rows or columns: \n");
scanf("%d",&n);
printf("Enter the square matrix: \n");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("The determinant is: \n");
int s=0;
s=determinant(A,n,i,s);
printf("%d\n",s);
fflush(stdin);
getchar();
return 0;
}
int determinant(int A[][100],int n,int i,int s)
{
int B[100][100];
int a=s;
if(n==2)
{
return A[0][0]*A[1][1] - A[0][1]*A[1][0];
}
else
{
//int s=0;
for(int j=0;j<n;j++)
{
int x=0;
for(int p=1;p<n;p++)
{
int y=0;
for(int q=0;q<n;q++)
{
if(q!=j)
{
B[x][y]=A[p][q];
y++;
}
}
x++;
}
if(j%2==0)
{
s+=A[0][j]*determinant(B,n-1,j,a);
}
else
{
s-=A[0][j]*determinant(B,n-1,j,a);
}
}
return s;
}
}
Output:
Enter the number of rows or columns: 4
Enter the square matrix:
1 13 4 6
23 21 18 5
4 2 7 9
1 10 15 12
The determinant is:
20353

No comments:

Post a Comment