Monday, May 27, 2024

A simple Java program to find the inverse of a given matrix

 import java.util.Scanner;

public class MatrixInverse { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = 2; double[][] matrix = new double[n][n]; double[][] inverse = new double[n][n]; System.out.println("Enter elements of 2x2 matrix:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = scanner.nextDouble(); } } double det = determinant(matrix); if (det == 0) { System.out.println("Matrix is singular, can't find its inverse."); } else { inverse(matrix, inverse, det); System.out.println("Inverse of the matrix is:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(inverse[i][j] + " "); } System.out.println(); } } } public static double determinant(double[][] matrix) { return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]); } public static void inverse(double[][] matrix, double[][] inverse, double det) { inverse[0][0] = matrix[1][1] / det; inverse[0][1] = -matrix[0][1] / det; inverse[1][0] = -matrix[1][0] / det; inverse[1][1] = matrix[0][0] / det; } }

A simple Java program to find the inverse of a given matrix

  import java.util.Scanner; public class MatrixInverse { public static void main (String[] args) { Scanner scanner =...