Java Program to multiply two matrices
Program
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args)
{
int mat1[][] = new int[10][10];
int mat2[][] = new int[10][10];
int result[][] = new int[10][10];
int row1, col1;
int row2, col2;
int i, j, k;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the number of rows and columns for matrix 1:");
System.out.println("Row 1:\t");
row1 = reader.nextInt();
System.out.println("Column 1:\t");
col1 = reader.nextInt();
System.out.println("Enter the number of rows and columns for matrix 2:");
System.out.println("Row 2:\t");
row2 = reader.nextInt();
System.out.println("Column 2:\t");
col2 = reader.nextInt();
if (col1 != row2)
{
System.out.println("Unable to perform matrix multiplication");
}
else
{
System.out.println("Enter elements for martix 1:");
for(i = 0; i < row1; i++)
{
for(j = 0; j < col1; j++)
{
mat1[i][j] = reader.nextInt();
}
}
System.out.println("Enter elements for martix 2:");
for(i = 0; i < row2; i++)
{
for(j = 0; j < col2; j++)
{
mat2[i][j] = reader.nextInt();
}
}
for(i = 0; i < row1; i++)
{
for(j = 0; j < col2; j++)
{
result[i][j] = 0;
for(k = 0; k < col1; k++)
{
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
System.out.println("Product matrix:");
for(i = 0; i < row1; i++)
{
for(j = 0; j < col2; j++)
{
System.out.printf("%d\t", result[i][j]);
}
System.out.println("\n");
}
}
}
}
Output 1
$ javac MatrixMultiplication.java
$ java MatrixMultiplication
Enter the number of rows and columns for matrix 1:
Row 1:
2
Column 1:
3
Enter the number of rows and columns for matrix 2:
Row 2:
3
Column 2:
3
Enter elements for martix 1:
2
3
1
2
-7
4
Enter elements for martix 2:
3
4
5
1
1
4
2
1
4
Product matrix:
11 12 26
7 5 -2
Output 2
$ java MatrixMultiplication
Enter the number of rows and columns for matrix 1:
Row 1:
2
Column 1:
2
Enter the number of rows and columns for matrix 2:
Row 2:
3
Column 2:
2
Unable to perform matrix multiplication