Write a Java Program to Multiply two Matrices by Passing Matrix to a Function

Java Program to Multiply two Matrices by Passing Matrix to a Function

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Multiply two Matrices by Passing Matrix to a Function
Java Program to Multiply two Matrices by Passing Matrix to a Function

Write a Java Program to Multiply two Matrices by Passing Matrix to a Function

PROGRAM: Java Program to Multiply two Matrices by Passing Matrix to a Function

/*Java Program to Multiply two Matrices by Passing Matrix to a Function*/

public class MultiplyMatrices {

public static void main(String[] args) {
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };

// Mutliplying Two matrices
int[][] product = multiplyMatrices(firstMatrix, secondMatrix, r1, c1, c2);

// Displaying the result
displayProduct(product);
}

public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix, int r1, int c1, int c2) {
int[][] product = new int[r1][c2];
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}

return product;
}

public static void displayProduct(int[][] product) {
System.out.println(“Product of two matrices is: “);
for(int[] row : product) {
for (int column : row) {
System.out.print(column + ” “);
}
System.out.println();
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *