Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Program to Check the Multiplicability of Two Matrices

  • Last Updated : 29 Oct, 2020

Given two matrices, the task to check Multiplicability of them. Matrices can either be square or rectangular. Matrices must have the same datatype.  Multiplicablity of the matrix depends on their ROWS and COLUMNS. If the Columns of the first matrix are equal to the Rows of the second matrix then both the matrices are multiplicable.

Example:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Input : mat1[][] = {{1, 2, 3}, 
                    {4, 5, 6}}
        mat2[][] = {{7,  8 }, 
                    {9,  10},
                    {11, 12}}
Output : Multiplication Possible
     Resultant matrix will have 2X2 dimension.

Input : mat1[][] = {{2, 4}, 
                    {3, 4},
            {1, 2}}
        mat2[][] = {{1, 2}, 
                    {1, 3}}       
Output : Multiplication Not Possible

Approach:

  1. Check Data-type of both the matrices.
  2. If Data-types are the same then proceed with the program.
  3. Else break the program and print not possible.
  4. If the number of columns in the first matrix is the same as the number of rows in the second matrix then print Possible and the dimension of the resultant matrix will be N x M, where N is the number of rows of the first matrix and M is the number of columns of the second matrix.
  5. Else print not possible.

Below is the implementation of the above approach.

Java




// Java Program to Check the 
// Multiplicability of Two Matrices
  
class GFG {
    
    public static void main(String[] args)
    {
        // Given Two Matrices
        int[][] matrixA = { { 1, 2, 3 }, { 4, 5, 6 } };
        int[][] matrixB
            = { { 7, 8 }, { 9, 10 }, { 11, 12 } };
  
        int row1 = matrixA.length;
        int column1 = matrixA[0].length;
        int row2 = matrixB.length;
        int column2 = matrixB[0].length;
  
        if (column1 == row2) {
            System.out.println("Multiplication Possible");
            System.out.println("Resultant matrix will have "
                               + row1 + "X" + column2
                               + " dimension.");
        }
        else
            System.out.println(
                "Multiplication Not Possible");
    }
}
Output
Multiplication Possible
Resultant matrix will have 2X2 dimension.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!