## Super friendly code & developer communities

A place for coders and developers to share, learn and grow together.

# Java Programming | Multiplication of matrices using 2d arrays.

This is a tutorial for multiplication of matrices using 2d arrays in java. The program is given below that takes two matrices from user and multiplies them and prints the product. The program is extendable. Go enjoy the program. Lets begin…

Program for multiplication of matrices using 2d arrays in java.

``````
//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class MatrixMultiply {
//void main
public static void main (String[] args)
{
//declare int
int i,j,k,s=0,a[][] = new int[10][10],b[][]= new int[10][10];

//Declare input as scanner
Scanner input = new Scanner(System.in);

//Take input for matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.println("Enter Number :");
a[i][j] = input.nextInt();
}
}

//Take input for other matrix
System.out.println("Enter Other Matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.println("Enter Number :");
b[i][j] = input.nextInt();
}
}

System.out.println("Product :-");
//print the product.
for(i=0;i<3;i++)
{
for(j=0;j<3;j++){

for(k=0;k<3;k++)
s=s+a[i][k]*b[k][j];

System.out.print(s+" ");
s=0;
}
System.out.print("\n");
}
}
}
``````

Output

Enter Number :
1
Enter Number :
2
Enter Number :
3
Enter Number :
1
Enter Number :
2
Enter Number :
3
Enter Number :
1
Enter Number :
2
Enter Number :
3
Enter Other Matrix
Enter Number :
1
Enter Number :
2
Enter Number :
3
Enter Number :
1
Enter Number :
2
Enter Number :
3
Enter Number :
1
Enter Number :
2
Enter Number :
3
Product :-
6 12 18
6 12 18
6 12 18

How does it work
1. You enter the number.
2. The number is saved in respective array for first matrix.
3. The number is saved in respective array for second matrix.
4. Then numbers are multiplied and printed to form of matrix.

Extending it
The program can be extended by using more numbers and making the matrix more bigger. Go extend it.

Explanation.
1. Import the Scanner.
2. Declare the class as public
3. Add the void main function
4. Declare input as Scanner.