Open In App

Java Program to Check the Multiplicability of Two Matrices

Last Updated : 22 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

Time Complexity: O(1), as we are not using any loops.

Auxiliary Space: O(1), as we are not using any extra space.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads