fork download
  1.  
  2. import java.io.*;
  3. class GFG {
  4. // Function to print Matrix
  5. static void printMatrix(int M[][], int rowSize,
  6. int colSize)
  7. {
  8. for (int i = 0; i < rowSize; i++) {
  9. for (int j = 0; j < colSize; j++)
  10. System.out.print(M[i][j] + " ");
  11.  
  12. System.out.println();
  13. }
  14. }
  15.  
  16. // Function to multiply
  17. // two matrices A[][] and B[][]
  18. static void multiplyMatrix(int row1, int col1,
  19. int A[][], int row2,
  20. int col2, int B[][])
  21. {
  22. int i, j, k;
  23.  
  24. // Print the matrices A and B
  25. System.out.println("\nMatrix A:");
  26. printMatrix(A, row1, col1);
  27. System.out.println("\nMatrix B:");
  28. printMatrix(B, row2, col2);
  29.  
  30. // Check if multiplication is Possible
  31. if (row2 != col1) {
  32.  
  33. System.out.println(
  34. "\nMultiplication Not Possible");
  35. return;
  36. }
  37.  
  38. // Matrix to store the result
  39. // The product matrix will
  40. // be of size row1 x col2
  41. int C[][] = new int[row1][col2];
  42.  
  43. // Multiply the two matrices
  44. for (i = 0; i < row1; i++) {
  45. for (j = 0; j < col2; j++) {
  46. for (k = 0; k < row2; k++)
  47. C[i][j] += A[i][k] * B[k][j];
  48. }
  49. }
  50.  
  51. // Print the result
  52. System.out.println("\nResultant Matrix:");
  53. printMatrix(C, row1, col2);
  54. }
  55.  
  56. // Driver code
  57. public static void main(String[] args)
  58. {
  59.  
  60. int row1 = 4, col1 = 3, row2 = 3, col2 = 4;
  61.  
  62. int A[][] = { { 1, 1, 1 },
  63. { 2, 2, 2 },
  64. { 3, 3, 3 },
  65. { 4, 4, 4 } };
  66.  
  67. int B[][] = { { 1, 1, 1, 1 },
  68. { 2, 2, 2, 2 },
  69. { 3, 3, 3, 3 } };
  70.  
  71. multiplyMatrix(row1, col1, A, row2, col2, B);
  72. }
  73. }
Success #stdin #stdout 0.13s 53636KB
stdin
Standard input is empty
stdout
Matrix A:
1 1 1 
2 2 2 
3 3 3 
4 4 4 

Matrix B:
1 1 1 1 
2 2 2 2 
3 3 3 3 

Resultant Matrix:
6 6 6 6 
12 12 12 12 
18 18 18 18 
24 24 24 24