# Java Program to Multiply Two Matrices

« Previous Program Next Program »

## Multiply Two Matrices

To multiply two matrices in Java Programming, you have to first ask to the user to enter the number of rows and columns of the first matrix and then ask to enter the first matrix elements. Again ask the same for the second matrix. Now start multiplying the two matrices and store the multiplication result inside any variable say sum and finally store the value of sum in the third matrix say multiply[ ][ ] at the equivalent index as shown in the following program.

## Java Programming Code to Multiply Two 3*3 Matrices

Following Java Program ask to the user to enter the two 3*3 matrices elements, to multiply them to form a new matrix which is the multiplication result of the two entered 3*3 matrices, then display the result on the screen:

```/* Java Program Example - Multiply two Matrices */

import java.util.Scanner;

public class JavaProgram
{
public static void main(String args[])
{

int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);

System.out.print("Enter Number of Rows and Columns of First Matrix : ");
m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];

System.out.print("Enter First Matrix Elements : ");

for(c=0 ; c<m; c++)
{
for(d=0; d<n; d++)
{
first[c][d] = in.nextInt();
}
}

System.out.print("Enter Number of Rows and Columns of Second Matrix : ");
p = in.nextInt();
q = in.nextInt();

if ( n != p )
{
System.out.print("Matrix of the entered order can't be Multiplied..!!");
}
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];

System.out.print("Enter Second Matrix Elements :\n");

for(c=0; c<p; c++)
{
for(d=0; d<q; d++)
{
second[c][d] = in.nextInt();
}
}

System.out.print("Multiplying both Matrix...\n");

for(c=0; c<m; c++)
{
for(d=0; d<q; d++)
{
for(k=0; k<p; k++)
{
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

System.out.print("Multiplication Successfully performed..!!\n");
System.out.print("Now the Matrix Multiplication Result is :\n");

for(c=0; c<m; c++)
{
for(d=0; d<q; d++)
{
System.out.print(multiply[c][d] + "\t");
}
System.out.print("\n");
}
}

}
}```

When the above Java Program is compile and executed, it will produce the following output:

### Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:

Java Online Test

« Previous Program