Java Online Compiler
Example: Multiplication of Two Matrix in Java of Same Dimensions using For loop
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Multiplication of Two Matrix in Java of Same Dimensions using For loop import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int r, c, i, j, k; // r - To store number of rows // c - To store number of columns System.out.println ("Enter the number of rows & columns of the matrix::\n"); r = in.nextInt(); c = in.nextInt(); int x[][], y[][], m[][]; x = new int[r + 1][c + 1]; y = new int[r + 1][c + 1]; m = new int[r + 1][c + 1]; // x - To store first matrix elements // y - To store second matrix elements // m - To store multiplication of matrices System.out.println ("\n---Enter the first matrix's elements---"); for (i = 0; i < r; i++) { for(j = 0; j < c; j++) { x[i][j] = in.nextInt(); } } System.out.println ("---Enter the second matrix's elements---"); for(i = 0; i < r; i++) { for(j = 0; j < c; j++) { y[i][j] = in.nextInt(); } } System.out.println ("\n\n-----The multiplication of the matrices is-----\n"); // It's the calculation of matrices's multiplications for(i = 0; i < r; i++) { for(j = 0; j < c; j++) { m[i][j] = 0; for(k = 0; k < c; k++) { m[i][j] += x[i][k] * y[k][j]; } } } // This will display matrices's outputs for(i = 0; i < r; i++) { System.out.print ("\t"); for(j = 0; j < c; j++) { System.out.print (m[i][j] + "\t"); } System.out.println ("\n"); } } }
3 4 12 32 43 54 21 34 54 22 23 45 56 67 12 34 56 76 12 43 54 54 12 54 76 34
Output
Clear
ADVERTISEMENTS