Program to multiply the two matrices with different dimensions.

import java.io.*;
class test
{
public static void main(String[] asd)throws IOException
{
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the values of Rows and Columns of Matrix-1.");
String num=obj.readLine();
int r1=Integer.parseInt(num);
num=obj.readLine();
int c1=Integer.parseInt(num);
int m1[][]= new int[r1][c1];
System.out.println("Enter the values of the matrix not more then "+(r1*c1)+".");
for(int i=0;i<r1;i++)
for(int j=0;j<c1;j++)
{
num=obj.readLine();
m1[i][j]=Integer.parseInt(num);
}
System.out.println("First matrix is::");
for(int i=0;i<r1;i++)
{    for(int j=0;j<c1;j++)
{
System.out.print(m1[i][j]+"    ");
}
System.out.println();
}
System.out.println("Enter the values of Rows and Columns of Matrix-2.");
num=obj.readLine();
int r2=Integer.parseInt(num);
num=obj.readLine();
int c2=Integer.parseInt(num);
int m2[][]= new int[r2][c2];
System.out.println("Enter the values of the matrix not more then "+(r2*c2)+".");
for(int i=0;i<r2;i++)
for(int j=0;j<c2;j++)
{
num=obj.readLine();
m2[i][j]=Integer.parseInt(num);
}
System.out.println("Second matrix is::");
for(int i=0;i<r2;i++)
{    for(int j=0;j<c2;j++)
{
System.out.print(m2[i][j]+"    ");
}
System.out.println();
}
int m3[][]=new int[r1][c2];
for(int i=0;i<r1;i++)
{for(int j=0;j<c2;j++)
{    m3[i][j]=0;
for(int k=0;k<r2;k++)
m3[i][j]+=m1[i][k]*m2[k][j];
}
}
System.out.println("After multiplication Matrix is::");
for(int i=0;i<r1;i++)
{    for(int j=0;j<c2;j++)
{
System.out.print(m3[i][j]+"    ");
}
System.out.println();
}

}




}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s