Write a Java program to find the Determinant of a 2 * 2 Matrix and 3 * 3 Matrix. The mathematical formula to find this Matrix determinant is as shown below.
Java program to find Determinant of a 2 * 2 Matrix
It is an example to find the Determinant of a 2 * 2 Matrix. This Java code allows user to enter the values of 2 * 2 Matrix using the For loop. Next, we used the mathematical formula to find the matrix determinant.
import java.util.Scanner; public class DeterminantOfMatrix { private static Scanner sc; public static void main(String[] args) { int[][] arr = new int[2][2]; int i, j, determinant = 0; sc= new Scanner(System.in); System.out.println("\n Please Enter the Matrix Items : "); for(i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { arr[i][j] = sc.nextInt(); } } determinant = (arr[0][0] * arr[1][1]) - (arr[0][1] * arr[1][0]); System.out.println("The Determinant of 2 * 2 Matrix = " + determinant ); } }
Java 3 * 3 Matrix Determinant
This Java code finds the determinant of a 3 * 3 matrix. So, this Java example allows the users to enter the 3 * 3 matrix items. Please refer to C program to find Matrix Determinant article to understand this determinant code’s analysis in iteration wise.
import java.util.Scanner; public class DeterminantOfMatrix { private static Scanner sc; public static void main(String[] args) { int[][] arr = new int[3][3]; int i, j, x, y, z, determinant = 0; sc= new Scanner(System.in); System.out.println("\n Please Enter the Matrix Items : "); for(i = 0; i < 3; i++) { for(j = 0; j < 3; j++) { arr[i][j] = sc.nextInt(); } } x = (arr[1][1] * arr[2][2]) - (arr[2][1] * arr[1][2]); y = (arr[1][0] * arr[2][2]) - (arr[2][0] * arr[1][2]); z = (arr[1][0] * arr[2][1]) - (arr[2][0] * arr[1][1]); determinant = (arr[0][0] * x)- (arr[0][1] * y) + (arr[0][2] * z); System.out.println("The Determinant of 3 * 3 Matrix = " + determinant ); } }
Java matrix Determinant output
Please Enter the Matrix Items :
10 20 30
40 50 60
70 80 90
The Determinant of 3 * 3 Matrix = 0