Sunday, August 21, 2011

Multiplication of two matrixs in java


//Multiplication of two matrixs in java
import java.io.*;
class arraymul
{
 public static void main(String[] arg)
  {
   int m,n,p,q;
   BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
   int a[ ][ ]=new int[30][30];
   int b[ ][ ]=new int[30][30];
   int c[ ][ ]=new int[30][30];
    try
    {
     System.out.print("Enter the number of  rows in first matrix: ");
      m=Integer.parseInt(in.readLine());
     System.out.print("Enter the number of column in first matrix: ");
      n=Integer.parseInt(in.readLine());
     System.out.print("Enter the number of  rows in second matrix: ");
     p=Integer.parseInt(in.readLine());
     System.out.print("Enter the number of column in second matrix: ");
      q=Integer.parseInt(in.readLine());
    if(n==p)
    {
      System.out.print("Enter the value of elements of first array: ");    
      for(int i=0;i< m;i++)
      {
       for(int j=0;j<n;j++)
       {      
        a[i][j]=Integer.parseInt(in.readLine());
        }
      }
System.out.print("Enter the value of elements of second array: ");    
      for(int i=0;i<p;i++)
      {
       for(int j=0;j<q;j++)
       {      
        b[i][j]=Integer.parseInt(in.readLine());
        }
      }
     for(int i=0;i< m;i++)
      {
       for(int j=0;j<q;j++)
         {     
          c[i][j]=0;
            for(int k=0;k<n;k++)
            {
                 c[i][j]+=a[i][k]*b[k][j];
             }
         }
      }
     System.out.println("First matrix:");
       for(int i=0;i< m;i++)
      {
       for(int j=0;j<n;j++)
       {      
        System.out.print(a[i][j]+" ");
        }
        System.out.println();
      }
     System.out.println("Second matrix:");
       for(int i=0;i<p;i++)
      {
       for(int j=0;j<q;j++)
       {      
        System.out.print(b[i][j]+" ");
        }
        System.out.println();
      }
      System.out.println("Multiplication of two matrixs:");
       for(int i=0;i< m;i++)
      {
       for(int j=0;j<q;j++)
       {      
        System.out.print(c[i][j]+" ");
        }
        System.out.println();
      }
    }
     else
       {
      System.out.print("Multiplication is not possible ");
       }
    }
    catch(Exception e){ }
   }
}

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More