Tuesday 15 March 2016

Matrix multiplication using java coding

Similar to addition we can also write multiplication coding in java.
The program explains you.



import java.io.*;
class matrmul
{
 public static void main(String args[])throws IOException
{
int i,n,m,j,x,y,a[][],b[][],c[][];

           
DataInputStream br =new DataInputStream(System.in);

System.out.println("Enter the number of rows for A");
m=Integer.parseInt (br.readLine());

System.out.println("Enter the number of columns for A");
n=Integer.parseInt (br.readLine());
a=new int[m][n];
System.out.println("Enter the A array Elements");
  for (i=0; i<m; i++)
  {
    for (j=0;j<n;j++)
    {
      a[i][j]=Integer.parseInt(br.readLine());
    }
  }

System.out.println("Enter the number of rows for B");
x=Integer.parseInt (br.readLine());

System.out.println("Enter the number of columns for B");
y=Integer.parseInt (br.readLine());

b=new int[x][y];
System.out.println("Enter the B array Elements");
  for (i=0; i<m; i++)
  {
   for (j=0;j<n;j++)
   {
     b[i][j]=Integer.parseInt(br.readLine());
   }
  }
 
if(n==x)                                                                                                           
{
c=new int[m][y];

for(int i =0; i<m;i++)
            {
   for(j=0;j<y;j++)
             {
             for(int k =0; k<y;k++)
              {                                                      c[i][j]= c[i][j]+a[i][k]*b[k][j];
              }
             }
 }
 for(i=0;i<m;i++)
 {
    for(j=0;j<y;j++)
     {
      System.out.println(c[i][j]+"/t");
      }                                                        System.out.println("/n");
 }
}
else
{System.out.println("Matrix Multiplication is not possible");
}
}
}


OUTPUT
C:\Documents and Settings\dcom358>H:

H:\>cd java

H:\Java>path=C:\jdk1.3\bin;

H:\Java>javac matrmul.java
Note: matrmul.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.

H:\Java>java matrmul                                      
Enter the number of rows for A
2
Enter the number of columns for A
2



Enter the A array Elements
1
2
3
4
Enter the number of rows for B
2
Enter the number of columns for B
2
Enter the B array Elements
1
2
3
4
Product is
7
10


15
22


No comments:

Post a Comment