Java Program to find Matrix Multiplication

Find Matrix Multiplication

In the following example, we will multiply the two given matrices (two-dimensional arrays).

Example

Java Compiler
public class myClass { public static void main(String[] args) { int i, j, k; int[][] arr1 = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1} }; int[][] arr2 = { {2, 2, 2}, {2, 2, 2}, {2, 2, 2} }; int[][] arr3 = new int[3][3]; System.out.println("Matrix A (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr1[i][j]); System.out.println(); } System.out.println("\nMatrix B (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr2[i][j]); System.out.println(""); } for(i=0; i<3; i++) { for(j=0; j<3; j++) { for(k=0; k<3; k++) arr3[i][j] = arr3[i][j] + arr1[i][k] * arr2[k][j]; } } System.out.println("\nMatrix Multiplication (A x B):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr3[i][j]); System.out.println(); } } }

In the following example, we will get the values for (3 x 3) Matrices A and B from the user and display the matrix multiplication.

Example

Java Compiler
import java.util.Scanner; public class myClass { public static void main(String[] args) { int i, j, k; int[][] arr1 = new int[3][3]; int[][] arr2 = new int[3][3]; int[][] arr3 = new int[3][3]; Scanner reader = new Scanner(System.in); System.out.println("Enter Matrix A (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) arr1[i][j] = reader.nextInt(); } System.out.println("\nEnter Matrix B (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) arr2[i][j] = reader.nextInt(); } for(i=0; i<3; i++) { for(j=0; j<3; j++) { for(k=0; k<3; k++) arr3[i][j] = arr3[i][j] + arr1[i][k] * arr2[k][j]; } } System.out.println("\nMatrix Multiplication (A x B):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr3[i][j]); System.out.println(); } } }

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author