Matrix Multiplication Program in Java

Amansingh Javatpoint
1 min readFeb 23, 2021

--

We can multiply two matrices in java using binary * operator and executing another loop. A matrix is also known as array of arrays. We can add, subtract and multiply matrices.

In case of matrix multiplication, one row element of first matrix is multiplied by all columns of second matrix.

Let’s see a simple example to multiply two matrices of 3 rows and 3 columns.

  1. public class MatrixMultiplicationExample{
  2. public static void main(String args[]){
  3. //creating two matrices
  4. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
  5. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
  6. //creating another matrix to store the multiplication of two matrices
  7. int c[][]=new int[3][3]; //3 rows and 3 columns
  8. //multiplying and printing multiplication of 2 matrices
  9. for(int i=0;i< 3;i++){
  10. for(int j=0;j< 3;j++){
  11. c[i][j]=0;
  12. for(int k=0;k< 3;k++)
  13. {
  14. c[i][j]+=a[i][k]*b[k][j];
  15. }//end of k loop
  16. System.out.print(c[i][j]+” “); //printing matrix element
  17. }//end of j loop
  18. System.out.println();//new line
  19. }
  20. }}

https://www.tutorialandexample.com/features-of-java/

https://www.tutorialandexample.com/java-tutorial/

--

--

No responses yet