Java program to multiply two matrix using multi dimensional arrays

Here's a Java program to multiply two matrices using multi-dimensional arrays:

re‮:ot ref‬theitroad.com
import java.util.Scanner;

public class MatrixMultiplication {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Getting input for first matrix
        System.out.print("Enter the number of rows of the first matrix: ");
        int m1 = sc.nextInt();
        System.out.print("Enter the number of columns of the first matrix: ");
        int n1 = sc.nextInt();

        int[][] mat1 = new int[m1][n1];
        System.out.println("Enter the elements of the first matrix:");

        for (int i = 0; i < m1; i++) {
            for (int j = 0; j < n1; j++) {
                mat1[i][j] = sc.nextInt();
            }
        }

        // Getting input for second matrix
        System.out.print("Enter the number of rows of the second matrix: ");
        int m2 = sc.nextInt();
        System.out.print("Enter the number of columns of the second matrix: ");
        int n2 = sc.nextInt();

        int[][] mat2 = new int[m2][n2];
        System.out.println("Enter the elements of the second matrix:");

        for (int i = 0; i < m2; i++) {
            for (int j = 0; j < n2; j++) {
                mat2[i][j] = sc.nextInt();
            }
        }

        // Checking if multiplication is possible
        if (n1 != m2) {
            System.out.println("Matrix multiplication is not possible");
        } else {
            // Creating result matrix
            int[][] result = new int[m1][n2];

            // Performing multiplication
            for (int i = 0; i < m1; i++) {
                for (int j = 0; j < n2; j++) {
                    for (int k = 0; k < n1; k++) {
                        result[i][j] += mat1[i][k] * mat2[k][j];
                    }
                }
            }

            // Printing the result matrix
            System.out.println("Resultant matrix after multiplication:");
            for (int i = 0; i < m1; i++) {
                for (int j = 0; j < n2; j++) {
                    System.out.print(result[i][j] + " ");
                }
                System.out.println();
            }
        }

        sc.close();
    }
}

This program takes two matrices as input from the user and then performs the multiplication of the matrices. It also checks if the multiplication is possible or not. If it is possible, then it prints the resultant matrix.