Java program to multiply entered matrix

Multiply entered matrix

This program illustrate the concept how to multiply entered matrix.

  • In this program “m=row” and “n=coloumn” for first matrix.
  • And “p=row” and “q=coloumn” for second matrix.
  • We can multiply two matrix if and only if rows of first matrix=coloumns of second matrix.

import java.util.*;
class scan
{
	public static void main(String arg[])
	{
 int a[][]=new int[15][15];
 int b[][]=new int[15][15];
 int c[][]=new int[15][15];
 int i,j,e,m,n,p,q,sum=0;
 Scanner kb=new Scanner(System.in);
System.out.println("Enter rows and coloumn of first matrix");
 m=kb.nextInt();
 n=kb.nextInt();
System.out.println("Enter First matrix row wise:-\n");
 for(i=0;i<m;i++)
  {
   for(j=0;j<n;j++)
    {
		a[i][j]=kb.nextInt();
 
    }
  }
   System.out.println("Enter rows and coloumn of second matrix");
p=kb.nextInt();
q=kb.nextInt();  
System.out.println("Enter Second matrix row wise:-\n");
  for(i=0;i<p;i++)
  {
   for(j=0;j<q;j++)
    {
		b[i][j]=kb.nextInt();
    }
  }
 if(n==p)
 {
 for(i=0;i<m;i++)
   {
    for(j=0;j<q;j++)
     {
       for(e=0;e<p;e++)
       {
	sum=sum+(a[i][e]*b[e][j]) ;
 
      }
      c[i][j]=sum;
      sum=0;
     }
   }
 
 }
 else
 {
  System.out.println("Matrix multiplication is not possible ");
 }
  System.out.println("Product of two matrix is :- \n");
 for(i=0;i<m;i++)
 {
  for(j=0;j<q;j++)
  {
   System.out.print("\t"+c[i][j]);
  }
   System.out.print("\n");
 }
 }}

OUTPUT

If their is only one row and coloumn

multiply entered matrix

If their are three rows and coloumns

multiply entered matrix


What is matrix?

  • It is a rectangular array arranged in rows and coloumns.
  • Suppose a matrix “A” is denoted by m x n order.Where m=rows and n=coloumns.
  • Individual item in matrix “A” will be denoted by “aij” where i=m and j=n.

How matrix multiplication takes place

If their is only one row and one coloumn

multiply entered matrix


Comment below if you are facing any problem


Also read

How to add two matrice in java
How to transpose a entered matrice in java program

Leave a Reply

Your email address will not be published. Required fields are marked *