-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeterminant_of_matrix.cpp
More file actions
83 lines (68 loc) · 1.91 KB
/
determinant_of_matrix.cpp
File metadata and controls
83 lines (68 loc) · 1.91 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//C++ program to find determinant of a matrix
#include <bits/stdc++.h>
using namespace std;
#define N 4
//Function to get determinant of matrix
int determinantOfMatrix(double mat[N][N],int n)
{
double num1,num2,det=1,total=1;// initialize result
int index;
//temporary array for storing row
double temp[n+1];
//loop for traversing the diagonal elements
for(int i=0;i<n;i++)
{
index=i;
while(index<n && mat[index][i]==0)
{
index++;
}
if(index==n) //if there is non zero element
{
//the determinant of matrix as zero
continue;
}
if(index != i)
{
//loop for swapping the diagonal element row and index row
for(int j=0;j<n;j++)
{
swap(mat[index][j],mat[i][j]);
}
//determinant aign changes when we shift rows
//go through determinant properties
det=det*(-1);
}
for(int j=0;j<n;j++)
{
temp[j]=mat[i][j];
}
//traversing every row below the diagonal element
for(int j=i+1;j<n;j++)
{
num1=temp[i];//value of diagonal element
num2=mat[j][i];//value of next row element
//traversing every column of row
//and multiplying toevery row
for(int k=0;k<n;k++)
{
//multiplying to make diagonal
//element and next row element
mat[j][k]=num1*mat[j][k]-num2*temp[k];
}
total=total*num1; //Det(kA)=kDet(A)
}
}
for(int i=0;i<n;i++)
{
det=det*mat[i][i];
}
return (det/total);
}
//Driver code
int main()
{
double mat[N][N]={{1,0,2,-1},{3,0,0,5},{2,3,4,5},{1,0,5,0}};
printf("Determinant of the matrix is :%d",determinantOfMatrix(mat,N));
return 0;
}