|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class MatrixMultiplication { |
| 4 | + |
| 5 | + public static void main(String[] args) { |
| 6 | + int lm1=1, hm1=1, lm2=1, hm2=1; //length of matrices 1/2; height of matrices 1/2 |
| 7 | + //minimum length is 1 |
| 8 | + |
| 9 | + Scanner getArrayLength = new Scanner(System.in); |
| 10 | + System.out.println("Enter length and height of Array 1: "); |
| 11 | + lm1 = getArrayLength.nextInt(); |
| 12 | + hm1 = getArrayLength.nextInt(); |
| 13 | + |
| 14 | + System.out.println("Enter length and height of Array 1: "); |
| 15 | + lm2 = getArrayLength.nextInt(); |
| 16 | + hm2 = getArrayLength.nextInt(); |
| 17 | + |
| 18 | + getArrayLength.close(); |
| 19 | + |
| 20 | + double array1[][] = new double[lm1][hm1]; |
| 21 | + double array2[][] = new double[lm2][hm2]; |
| 22 | + |
| 23 | + //enter elements in array 1 |
| 24 | + System.out.println("Enter the elements of first array: "); |
| 25 | + Scanner sm = new Scanner(System.in); |
| 26 | + for(int x = 0; x <lm1; x++) { |
| 27 | + for (int y = 0; y< hm1; y++) { |
| 28 | + array1[x][y]= sm.nextDouble(); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + //enter elements in array 1 |
| 33 | + System.out.println("---\nEnter the elements of second array: "); |
| 34 | + for(int x = 0; x <lm2; x++) { |
| 35 | + for (int y = 0; y< hm2; y++) { |
| 36 | + array2[x][y]= sm.nextDouble(); |
| 37 | + } |
| 38 | + } |
| 39 | + sm.close(); // closing the scanner |
| 40 | + |
| 41 | + multiplication(array1, array2, lm1, lm2, hm1, hm2); |
| 42 | + |
| 43 | + System.out.println("---\nThe Program has ended."); |
| 44 | + } |
| 45 | + |
| 46 | + static double multiplication(double[][] array1, double[][] array2, int lm1, int lm2, int hm1, int hm2) { |
| 47 | + double result = 0, temp=0; |
| 48 | + for(int i=0;i<lm1;i++) { |
| 49 | + for(int j=0; j<hm2; j++) { |
| 50 | + temp = array1[i][j]* array2[j][i]; |
| 51 | + result = result + temp; |
| 52 | + System.out.println(array1[i][j] +" * "+ array2[j][i]+ " temp = "+temp+" res = "+result); |
| 53 | + |
| 54 | + } |
| 55 | + } |
| 56 | + System.out.println("The final result of multiplication is: "+result); |
| 57 | + return result; |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments