mhdew

multiplication of matrix

May 31st, 2018
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. package problem.pkg11;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Problem11 {
  6.  
  7.     public static void main(String[] args) {
  8.         Scanner scan=new Scanner(System.in);
  9.        
  10.         //Multiplication of two square matrix
  11.      
  12.         //int n=scan.nextInt();
  13.         int m1=scan.nextInt();
  14.         int n1=scan.nextInt();
  15.        
  16.         int a[][]=new int [m1+1][n1+1];
  17.        
  18.         for(int i=1;i<=m1;i++){
  19.             for(int j=1;j<=n1;j++){
  20.                 a[i][j]=scan.nextInt();
  21.             }
  22.         }
  23.        
  24.         int m2=scan.nextInt();
  25.         int n2=scan.nextInt();
  26.        
  27.         int b[][]=new int [m2+1][n2+1];
  28.        
  29.         for(int i=1;i<=m2;i++){
  30.             for(int j=1;j<=n2;j++){
  31.                 b[i][j]=scan.nextInt();
  32.             }
  33.         }
  34.        
  35.         if(n1!=m2){
  36.             System.out.println("Multiplication not possible");
  37.         }
  38.         else{
  39.             int c[][]=new int[m1+1][n2+1];
  40.  
  41.  
  42.             int sum;
  43.             for(int i=1;i<=m1;i++){
  44.                 for(int j=1;j<=n2;j++){
  45.                     sum=0;
  46.                     for(int k=1;k<=m2;k++){
  47.                         sum+=(a[j][k]*b[k][j]);
  48.                     }
  49.                     c[i][j]=sum;                
  50.                 }
  51.             }
  52.  
  53.             for(int i=1;i<=m1;i++){
  54.                 for(int j=1;j<=n2;j++){
  55.                     System.out.print(c[i][j]+" ");
  56.                 }
  57.                 System.out.printf("\n");
  58.             }
  59.         }
  60.        
  61.     }
  62.    
  63. }
Advertisement
Add Comment
Please, Sign In to add comment