Skip to content
UniCircle
EasyCodingArrays (2-D)

Multiply two matrices with 2-D arrays

Question JAVA-COD-106

Read matrix A (r × k) and matrix B (p × c). If they cannot be multiplied (k ≠ p), print INVALID. Otherwise print the r × c product, one row per line.

Use long[][] arrays in Java.

Constraints

  • 1 ≤ r, k, p, c ≤ 100
  • −1000 ≤ entries ≤ 1000

Input and output

Input
Line: r k, then r lines of A. Line: p c, then p lines of B.
Output
The product matrix, or `INVALID`.

Examples

Input 1

2 3
1 2 3
4 5 6
3 2
7 8
9 10
11 12

Output

58 64
139 154

Row 1: 1·7 + 2·9 + 3·11 = 58 and 1·8 + 2·10 + 3·12 = 64.

Input 2

1 2
1 2
3 1
1
2
3

Output

INVALID

A has 2 columns but B has 3 rows, so INVALID.

Show hints
  • C[i][j] is the dot product of row i of A and column j of B.
  • Looping i, t, j (instead of i, j, t) reads memory in row order and is faster.
Show the explanation

The product exists only when A's column count equals B's row count. Then C[i][j] = Σ A[i][t] · B[t][j] over t. Three nested loops give O(r · k · c). Ordering the loops i → t → j lets the inner loop walk rows of B and C contiguously, which is friendlier to the CPU cache than i → j → t. Use long because sums of products can exceed int.

Original UniCircle question. Last reviewed 22 Oct 2026.