Skip to content

Commit 668300a

Browse files
authored
Determinant_of_Matrix
1 parent ee573bb commit 668300a

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

Determinant_of_Matrix.java

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// Java program to find Determinant of a matrix
2+
class GFG {
3+
4+
// Dimension of input square matrix
5+
static final int N = 4;
6+
7+
// Function to get determinant of matrix
8+
static int determinantOfMatrix(int mat[][], int n)
9+
{
10+
int num1, num2, det = 1, index,
11+
total = 1; // Initialize result
12+
13+
// temporary array for storing row
14+
int[] temp = new int[n + 1];
15+
16+
// loop for traversing the diagonal elements
17+
for (int i = 0; i < n; i++) {
18+
index = i; // initialize the index
19+
20+
// finding the index which has non zero value
21+
while (mat[index][i] == 0 && index < n) {
22+
index++;
23+
}
24+
if (index == n) // if there is non zero element
25+
{
26+
// the determinant of matrix as zero
27+
continue;
28+
}
29+
if (index != i) {
30+
// loop for swaping the diagonal element row
31+
// and index row
32+
for (int j = 0; j < n; j++) {
33+
swap(mat, index, j, i, j);
34+
}
35+
// determinant sign changes when we shift
36+
// rows go through determinant properties
37+
det = (int)(det * Math.pow(-1, index - i));
38+
}
39+
40+
// storing the values of diagonal row elements
41+
for (int j = 0; j < n; j++) {
42+
temp[j] = mat[i][j];
43+
}
44+
45+
// traversing every row below the diagonal
46+
// element
47+
for (int j = i + 1; j < n; j++) {
48+
num1 = temp[i]; // value of diagonal element
49+
num2 = mat[j]
50+
[i]; // value of next row element
51+
52+
// traversing every column of row
53+
// and multiplying to every row
54+
for (int k = 0; k < n; k++) {
55+
// multiplying to make the diagonal
56+
// element and next row element equal
57+
mat[j][k] = (num1 * mat[j][k])
58+
- (num2 * temp[k]);
59+
}
60+
total = total * num1; // Det(kA)=kDet(A);
61+
}
62+
}
63+
64+
// multiplying the diagonal elements to get
65+
// determinant
66+
for (int i = 0; i < n; i++) {
67+
det = det * mat[i][i];
68+
}
69+
return (det / total); // Det(kA)/k=Det(A);
70+
}
71+
72+
static int[][] swap(int[][] arr, int i1, int j1, int i2,
73+
int j2)
74+
{
75+
int temp = arr[i1][j1];
76+
arr[i1][j1] = arr[i2][j2];
77+
arr[i2][j2] = temp;
78+
return arr;
79+
}
80+
81+
// Driver code
82+
public static void main(String[] args)
83+
{
84+
int mat[][] = { { 1, 0, 2, -1 },
85+
{ 3, 0, 0, 5 },
86+
{ 2, 1, 4, -3 },
87+
{ 1, 0, 5, 0 } };
88+
89+
// Function call
90+
System.out.printf(
91+
"Determinant of the matrix is : %d",
92+
determinantOfMatrix(mat, N));
93+
}
94+
}

0 commit comments

Comments
 (0)