import java.io.*;
class Matrix
{
public static void main ( String args[] )
throws IOException
{
BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) );
System.out.println("\n\nEnter rows and columns for 1st Matrix -\n\n");
System.out.print("Rows : ");
int r1 = Integer.parseInt( br.readLine() );
System.out.print("\nColumns : ");
int c1 = Integer.parseInt( br.readLine() );
System.out.println("\n\nEnter rows and columns for 2nd Matrix -\n\n");
System.out.print("Rows : ");
int r2 = Integer.parseInt( br.readLine() );
System.out.print("\nColumns : ");
int c2 = Integer.parseInt( br.readLine() );
int m1[][] = new int[r1][c1];
int m2[][] = new int[r2][c2];
int m[][] = new int[r1][c2];
if ( r1 != c2 )
{
System.out.println("\n\nMultiplication not possible...\n");
System.out.println("\nRows of matrix 1 should be equal to Columns of matrix 2 !\n");
}
else
{
System.out.println("\n\nMultiplication possible...");
System.out.println("\n\nEnter values for Matrix 1 -\n");
for ( int i=0 ; i<r1 ; i++ )
{
for ( int j=0 ; j<c1 ; j++ )
{
System.out.print("\nEnter element [" + i + "][" + j + "] : ");
m1[i][j] = Integer.parseInt( br.readLine() );
}
}
System.out.println("\n\nEnter values for Matrix 2 -\n");
for ( int i=0 ; i<r2 ; i++ )
{
for ( int j=0 ; j<c2 ; j++ )
{
System.out.print("\nEnter element [" + i + "][" + j + "] : ");
m2[i][j] = Integer.parseInt( br.readLine() );
}
}
for ( int i=0 ; i<r1 ; i++ )
{
for ( int j=0 ; j<c2 ; j++ )
{
m[i][j] = 0;
for ( int k=0 ; k<3 ; k++ )
m[i][j] = m[i][j] + m1[i][k] * m2[k][j];
}
}
System.out.println("\n\nMultiplication -\n\n");
for ( int i=0 ; i<r1 ; i++ )
{
for ( int j=0 ; j<c2 ; j++ )
System.out.print(m[i][j] + " ");
System.out.println("\n");
}
}
}
}
No comments:
Post a Comment