Matrix Multiplication in Java
In this Java tutorial we will demonstrate you 'Matrix Multiplication in Java' with the help of a simple example from which you can easily learn how to write a matrix multiplication program in Java.
This example shows you how to write a program using Java to multiply two matrixes to each other. In addition to that, you can also access Java source code to make you understand about the Java developing application program.
Here, we will write a simple program, which will multiply two matrix. A Two dimensional array represents the matrix.
Here we will write a simple java program in order to multiply two matrix
To initiate with the program, you have to declare two multidimensional array of type integer. This program uses two for loops in order to get number of rows and columns by using the array1.length. Once you get both the matrix, multiply to it. Both the matrix will multiply to each other by using 'for' loop. And finally, the output will be shown in the screen command prompt by using the println() method.
Here is the Example for writing Matrix Multiplication program in Java in simple steps:
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: Matrix Multiplication in Java
Post your Comment