4. Program to subtract the two matrices.
💡Code:
import java.util.Scanner; public class SubtractMatrices { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Get the dimensions of the matrices from the user System.out.print("Enter the number of rows: "); int rows = scanner.nextInt(); System.out.print("Enter the number of columns: "); int columns = scanner.nextInt(); // Create the first matrix int[][] matrix1 = new int[rows][columns]; System.out.println("Enter elements for the first matrix:"); inputMatrix(matrix1, scanner); // Create the second matrix int[][] matrix2 = new int[rows][columns]; System.out.println("Enter elements for the second matrix:"); inputMatrix(matrix2, scanner); // Subtract the matrices int[][] differenceMatrix = subtractMatrices(matrix1, matrix2); // Display the result System.out.println("Difference of the matrices:"); printMatrix(differenceMatrix); // Close the scanner scanner.close(); } // Function to input elements into a matrix private static void inputMatrix(int[][] matrix, Scanner scanner) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print("Enter element at position [" + (i + 1) + "][" + (j + 1) + "]: "); matrix[i][j] = scanner.nextInt(); } } } // Function to subtract two matrices private static int[][] subtractMatrices(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int columns = matrix1[0].length; int[][] differenceMatrix = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { differenceMatrix[i][j] = matrix1[i][j] - matrix2[i][j]; } } return differenceMatrix; } // Function to print a matrix private static void printMatrix(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); // Move to the next row } } }
📸Output :
.png)