» » Multiply two matrices

  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class Multiply2Matrices{
  6.  
  7.    public static void main(String args[])
  8.    {
  9.  
  10.       int m, n, p, q, sum = 0, c, d, k;
  11.  
  12.       Scanner in = new Scanner(System.in);
  13.  
  14.       System.out.println("Enter the number of rows and columns of first matrix");
  15.  
  16.       m = in.nextInt();
  17.       n = in.nextInt();
  18.  
  19.       int first[][] = new int[m][n];
  20.  
  21.      System.out.println("Enter the elements of first matrix");
  22.  
  23.       for ( c = 0 ; c < m ; c++ )
  24.          for ( d = 0 ; d < n ; d++ )
  25.             first[c][d] = in.nextInt();
  26.  
  27.       System.out.println("Enter the number of rows and columns of second matrix");
  28.  
  29.       p = in.nextInt();
  30.       q = in.nextInt();
  31.  
  32.      if ( n != p )
  33.          System.out.println("Matrices with entered orders can't be multiplied with each other.");
  34.       else
  35.       {
  36.          int second[][] = new int[p][q];
  37.          int multiply[][] = new int[m][q];
  38.          System.out.println("Enter the elements of second matrix");
  39.  
  40.          for ( c = 0 ; c < p ; c++ )
  41.             for ( d = 0 ; d < q ; d++ )
  42.                second[c][d] = in.nextInt();
  43.  
  44.          for ( c = 0 ; c < m ; c++ )
  45.          {
  46.             for ( d = 0 ; d < q ; d++ )
  47.             {   
  48.                for ( k = 0 ; k < p ; k++ )
  49.                {
  50.                   sum = sum + first[c][k]*second[k][d];
  51.                }
  52.                multiply[c][d] = sum;
  53.                sum = 0;
  54.             }
  55.          }
  56.  
  57.          System.out.println("Multiplication of entered matrices:-");
  58.  
  59.          for ( c = 0 ; c < m ; c++ )
  60.          {
  61.             for ( d = 0 ; d < q ; d++ )
  62.                System.out.print(multiply[c][d]+"\t");
  63.             System.out.print("\n");
  64.          }
  65.  
  66.       }
  67.  
  68.    }
  69. }  

OutPut:


  1. Enter the number of rows and columns of first matrix
  2.  
  3. 2 2
  4.  
  5. Enter the elements of first matrix
  6.  
  7. 2 2
  8. 2 3
  9.  
  10. Enter the number of rows and columns of second matrix
  11.  
  12. 2 2
  13.  
  14. Enter the elements of second matrix
  15.  
  16. 1 1
  17. 1 1
  18.  
  19. Multiplication of entered matrices:-
  20.  
  21. 4    4    
  22. 5    5  


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu