Write a Java program to multiply two matrices. Ensure that the number of columns in the first matrix is equal to the number of rows in the second matrix.
Given matrices:
Matrix A (2x3):
1 2 3 4 5 6
Matrix B (3x2):
7 8 9 10 11 12
Single Choice
Views 31
Answer:
public class Main { public static void main(String[] args) { int[][] matrixA = { {1, 2, 3}, {4, 5, 6} }; int[][] matrixB = { {7, 8}, {9, 10}, {11, 12} }; int[][] result = new int[2][2]; for (int i = 0; i < matrixA.length; i++) { for (int j = 0; j < matrixB[0].length; j++) { for (int k = 0; k < matrixA[0].length; k++) { result[i][j] += matrixA[i][k] * matrixB[k][j]; } } } // Print result for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[i].length; j++) { System.out.print(result[i][j] + " "); } System.out.println(); } } }
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.