Write a program to find determinant of a matrix


Default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Write a program to find determinant of a matrix
// Author: AimForJob.com
 
#include
#include
int determinant(int m, int a[][]);
int main(){
     int n,i,j;
     printf("Enter order of matrix:");
     scanf("%d",&n);                 // matrix row size input from user
     int matrix[n][n];
    
     // user input for matrix elements
     printf("Enter Matrix Elements\n");
     for(i=0;i<n;i++){
             for(j=0;j<n;j++){
                     scanf("%d",&matrix[i][j]);
             }
     }
     for(i=0;i<n;i++){
            for(j=0;j<n;j++){
                     printf("%d ",matrix[i][j]);
            }
            printf("\n");
     }
     int det = determinant(n,matrix);
     printf("Determinant :%d",det);               // calling determinant function
     getch();
}
int determinant(int m, int a[m][m]){
     if(m==1){
             return a[0][0];
     }
     else if(m==2){
             return a[0][0]*a[1][1]-a[0][1]*a[1][0];
     }
     else{
             int det = 0,s=0,t=0,i,j,k,x,y;
             for (i=0;i<m;i++){
                 int b[m-1][m-1];
                 for(j=0;j<m;j++){
                     if(j!=0){
                         for(k=0;k<m;k++){
                             if(k!=i){
                                 b[s][t] = a[j][k];    
                                 t++;
                             }
                         }
                     s++;
                     }
                    t = 0;
                }
                s = 0;
                det = det+(int)pow(-1,i)*a[0][i]*determinant(m-1,b);
}
            return det;  
     }
}

No comments:

Post a Comment