Continuous Test Orchestration And Execution Platform Online

Perform automated and live-interactive testing on 3000+ real desktop and mobile devices online.

Write a Java program to multiply two matrices?

There are several ways to perform matrix multiplication in Java, one of which is by using the binary operator (*) and implementing an additional loop. During the matrix multiplication process, all elements in the first matrix are multiplied by all elements in the second matrix corresponding to each row of the first matrix.

Here is the Java program to multiply two matrices.

``````import java.util.Scanner;
public class MatrixM {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x, y, m, n;
System.out.print("Enter the number of rows in the first matrix:");
x = sc.nextInt();
System.out.print("Enter number of columns in the first matrix:");
y = sc.nextInt();
System.out.print("Enter the number of rows in the second matrix:");
m = sc.nextInt();
System.out.print("Enter the number of columns in the second matrix:");
n = sc.nextInt();
int a[][] = new int[x][y];
int b[][] = new int[m][n];
System.out.println("Enter all the elements of first matrix:");
for (int i = 0; i < x; i) {
for (int j = 0; j < y; j) {
a[i][j] = sc.nextInt();
}
}
System.out.println("");
System.out.println("Enter all the elements of second matrix:");
for (int i = 0; i < m; i) {
for (int j = 0; j < n; j) {
b[i][j] = sc.nextInt();
}
}
System.out.println("First Matrix:");
for (int i = 0; i < x; i) {
for (int j = 0; j < y; j) {
System.out.print(a[i][j]
" ");
}
System.out.println("");
}
System.out.println("Second Matrix:");
for (int i = 0; i < m; i) {
for (int j = 0; j < n; j) {
System.out.print(b[i][j]
" ");
}
System.out.println("");
}
if (m != y) {
System.out.println("Multiplication Not Possible");
return;
}
int c[][] = new int[y][n];
int l = 0;
for (int i = 0; i < x; i) {
for (int j = 0; j < n; j) {
for (l = 0; l < m; l)
c[i][j] = a[i][l] * b[l][j];
}
}
System.out.println("Resultant Matrix is:");
for (int i = 0; i < y; i) {
for (int j = 0; j < n; j) {
System.out.print(c[i][j]
" ");
}
System.out.println("");
}
}
}``````

Test your websites, web-apps, or mobile apps seamlessly with LambdaTest.

Start Free Testing