Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /*
- * Program multiply two matrices
- * @author Steve Robinson
- * @see footyntech.wordpress.com
- */
- class MatMul
- {
- public static void main(String arg[])
- {
- int m,n,i,j;
- Scanner in=new Scanner(System.in);
- System.out.println("Enter the order of the first matrix [row, col]: ");
- m=in.nextInt();
- n=in.nextInt();
- int[][]matA=new int[m][n];
- System.out.println("Enter the elements of the matrix [row by row]: ");
- for(int a=0;a<m;a++)
- for(int b=0;b<n;b++)
- matA[a][b]=in.nextInt();
- System.out.println("Enter the order of the second matrix [row, col]: ");
- i=in.nextInt();
- j=in.nextInt();
- if(n!=i)
- {
- System.out.println("Invalid order. Multiplication Impossible!");
- System.exit(0);
- }
- int[][]matB=new int[i][j];
- int[][]matR=new int[m][j];
- System.out.println("Enter the elements of the second matrix [row by row]: ");
- for(int a=0;a<i;a++)
- for(int b=0;b<j;b++)
- matB[a][b]=in.nextInt();
- System.out.println("\nThe Matrix 1:");
- for(int a=0;a<m;a++)
- {
- for(int b=0;b<n;b++)
- System.out.print(matA[a][b]+" ");
- System.out.println();
- }
- System.out.println("\nThe Matrix 2:");
- for(int a=0;a<i;a++)
- {
- for(int b=0;b<j;b++)
- System.out.print(matB[a][b]+" ");
- System.out.println();
- }
- for(int a=0;a<m;a++)
- for(int b=0;b<j;b++)
- {
- matR[a][b]=0;
- for(int c=0;c<n;c++)
- matR[a][b]+=matA[a][c]*matB[c][b];
- }
- System.out.println("\nThe Result of Multiplication:");
- for(int a=0;a<m;a++)
- {
- for(int b=0;b<j;b++)
- System.out.print(matR[a][b]+" ");
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement