Write a program in Java to multiply two matrix

Here is a sample Java program to multiply two matrices.
This program takes the number of rows and columns of both matrices as input, followed by the elements of the matrices. It then performs the matrix multiplication and outputs the result. Note that it checks if the number of columns of the first matrix is equal to the number of rows of the second matrix, which is a necessary condition for matrix multiplication. If the condition is not met, the program outputs an error message.





The code :
-----------------------------------------------

import java.util.Scanner;


public class MatrixMultiplication {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix:");
int rowsA = scan.nextInt();
int columnsA = scan.nextInt();
int[][] matrixA = new int[rowsA][columnsA];
System.out.println("Enter the elements of first matrix:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < columnsA; j++) {
matrixA[i][j] = scan.nextInt();
}
}
System.out.println("Enter the number of rows and columns of second matrix:");
int rowsB = scan.nextInt();
int columnsB = scan.nextInt();
int[][] matrixB = new int[rowsB][columnsB];
System.out.println("Enter the elements of second matrix:");
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < columnsB; j++) {
matrixB[i][j] = scan.nextInt();
}
}
if (columnsA != rowsB) {
System.out.println("Matrices cannot be multiplied with the given dimensions.");
} else {
int[][] result = new int[rowsA][columnsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < columnsB; j++) {
for (int k = 0; k < columnsA; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
System.out.println("The result is:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < columnsB; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
}



-----------------------------------------------
Output:

                        

Comments