In this section we will learn about multiplication of two matrices. In java this is a simple program to multiply two matrices, we have to take twodimensional array and the result should be saved in third twodimensional array. Here we are going to develop a Java code for matrices multiplication, while multiplying two matrices the number of column in first matrix is equal to number of rows in second matrix, and both array will initialize with the number of rows and column given by user. Two for loop is used, one which executes up to the number of rows and second one will execute up to the number of column. After getting the number of rows, number of columns and element of both arrays, multiply both and store it in resultant array that is c.
import java.util.Scanner; class MatrixMultiplication { public static void main(String args[]) { int m, n, p, q, sum = 0, i, j, k; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows and columns of first matrix"); m = in.nextInt(); n = in.nextInt(); int a[][] = new int[m][n]; //creating array and initialize to the row and column of first matrix System.out.println("Enter the elements of first matrix"); for ( i = 0 ; i < m ; i++ ) for ( j = 0 ; j < n ; j++ ) a[i][j] = in.nextInt(); System.out.println("Enter the number of rows and columns of second matrix"); p = in.nextInt(); //p holding the number of rows for the second matrix q = in.nextInt(); // q holding the number of column for the second matrix. if ( n != p ) System.out.println("Matrix orders can't be multiplied with each other."); else { int b[][] = new int[p][q]; int c[][] = new int[m][q]; System.out.println("Enter the elements of second matrix"); for ( i = 0 ; i < p ; i++ ) for ( j = 0 ; j < q ; j++ ) b[i][j] = in.nextInt(); for ( i = 0 ; i < m ; i++ ) // logic for multiplication { for ( j = 0 ; j < q ; j++ ) { for ( k = 0 ; k < p ; k++ ) { sum = sum + a[i][k]*b[k][j]; } c[i][j] = sum; sum = 0; } } System.out.println("Product of the two matrices:"); for ( i = 0 ; i < m ; i++ ) //printing after multiplying two matrices. { for ( j = 0 ; j < q ; j++ ) System.out.print(c[i][j]+"\t"); System.out.print("\n"); } } } }
Output : After compiling and executing above program
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial

Discuss: Matrix multiplication in java
Post your Comment