|
| 1 | +// Q. matrix multiplication in java ? |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +public class matrix_Multiplication { |
| 6 | + public static void main(String args[]) { |
| 7 | + |
| 8 | + int m, n, p, q, sum = 0, c, d, k; |
| 9 | + Scanner in = new Scanner(System.in); |
| 10 | + |
| 11 | + System.out.print("Enter Number of Rows and Columns of First Matrix : "); |
| 12 | + m = in.nextInt(); // enter no. of rows of first matrix |
| 13 | + n = in.nextInt(); // enter no. of vplumns of first matrix |
| 14 | + |
| 15 | + int first[][] = new int[m][n]; |
| 16 | + |
| 17 | + System.out.print("Enter First Matrix Elements : "); |
| 18 | + |
| 19 | + for (c = 0; c < m; c++) { |
| 20 | + for (d = 0; d < n; d++) { |
| 21 | + first[c][d] = in.nextInt(); // here we have to enter first matrix's element |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + System.out.print("Enter Number of Rows and Columns of Second Matrix : "); |
| 26 | + p = in.nextInt(); // enter no. of vplumns of second matrix |
| 27 | + q = in.nextInt(); // enter no. of vplumns of second matrix |
| 28 | + |
| 29 | + if (n != p) { |
| 30 | + System.out.print("Matrix of the entered order can't be Multiplied..!!"); |
| 31 | + } else { |
| 32 | + int second[][] = new int[p][q]; |
| 33 | + int multiply[][] = new int[m][q]; |
| 34 | + |
| 35 | + System.out.print("Enter Second Matrix Elements :\n"); |
| 36 | + |
| 37 | + for (c = 0; c < p; c++) { |
| 38 | + for (d = 0; d < q; d++) { |
| 39 | + second[c][d] = in.nextInt(); // here we have to enter second matrix's element |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + System.out.print("Multiplying both Matrix...\n"); |
| 44 | + |
| 45 | + for (c = 0; c < m; c++) { |
| 46 | + for (d = 0; d < q; d++) { |
| 47 | + for (k = 0; k < p; k++) { |
| 48 | + sum = sum + first[c][k] * second[k][d]; |
| 49 | + } |
| 50 | + |
| 51 | + multiply[c][d] = sum; // here sum is the element of multiply matrix and one by one element will be inserted |
| 52 | + sum = 0; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + System.out.print("Multiplication Successfully performed..!!\n"); |
| 57 | + System.out.print("Now the Matrix Multiplication Result is :\n"); |
| 58 | + |
| 59 | + for (c = 0; c < m; c++) { |
| 60 | + for (d = 0; d < q; d++) { |
| 61 | + System.out.print(multiply[c][d] + "\t"); // multiply matrix output |
| 62 | + } |
| 63 | + System.out.print("\n"); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + } |
| 68 | +} |
0 commit comments