Search This Blog

Wednesday 6 July 2016

Matrix Multiplication - java

package pl;
import java.util.Scanner;

public class Pl {

    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 1st matrix");
      m = in.nextInt();
      n = in.nextInt();
      int a[][] = new int[m][n];

      System.out.println("Enter the data of 1st 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 2nd matrix");
      p = in.nextInt();
      q = in.nextInt();

      if ( n != p )
         System.out.println("Matrices can't be multiplied !.");
      else
      {
         int b[][] = new int[p][q];
         int c[][] = new int[m][q];

         System.out.println("Enter data of 2nd matrix");

         for ( i = 0 ; i < p ; i++ )
            for ( j = 0 ; j < q ; j++ )
               b[i][j] = in.nextInt();

         for ( i = 0 ; i < m ; i++ )
         {
            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("Multiplication is :");

         for ( i = 0 ; i < m ; i++ )
         {
            for ( j = 0 ; j < q ; j++ )
               System.out.print(c[i][j]+" ");

            System.out.print("\n");
         }
      }
   }
 
}


output:

Enter the number of rows and columns of 1st matrix
3
3
Enter the data of 1st matrix:
1
2
3
4
5
6
7
8
9
Enter the number of rows and columns of 2nd matrix
3
3
Enter data of 2nd matrix
9
8
7
6
5
4
3
2
1
Multiplication is :
30 24 18
84 69 54
138 114 90

No comments:

Post a Comment