- From
- 3×3 reference
Perform Matrix Multiplication in C#
What you’ll learn
- The dimension rule: multiply
m×nbyn×pto getm×p. - How to implement the classic triple nested loop with row–column dot products in C#.
- Two programs: 3×3 reference demo and 2×2 with validation, plus a live 2×2 preview.
Overview
Matrix multiplication is the step up from addition and element-wise division: each result cell combines an entire row from the first matrix with a column from the second. Master the three-loop pattern and you unlock graphics, ML basics, and many interview questions.
Two programs
3×3 full demo and 2×2 with dimension guard.
Live preview
Multiply two editable 2×2 matrices instantly.
Dot products
Each C[i,j] = row i of A · column j of B.
Prerequisites
2D arrays and nested loops — complete matrix addition first if 2D arrays are new.
int[,],GetLength(0)(rows),GetLength(1)(columns).- Comfort with three nested
forloops (i, j, k).
What is matrix multiplication?
To find C[i,j], take row i of matrix A and column j of matrix B. Multiply matching entries and add them — a dot product.
If A is m × n and B is n × p, then C = A × B is m × p. The shared inner size n (columns of A, rows of B) must match.
Formal definition
Cij = Σk=0n-1 Aik × Bkj where n is the column count of A (and row count of B).
1×9 + 2×6 + 3×3 = 30 for the reference 3×3 matrices.
Quick examples
- Top row
- [[1,2],[3,4]]×[[5,6],[7,8]]
Loop mnemonic: i = result row, j = result column, k = shared index along the dot product.
Live preview
Edit two 2×2 matrices. The widget runs the triple-loop product.
Algorithm
Goal: compute C = A × B when cols(A) = rows(B).
Check dimensions
colsA = A.GetLength(1) must equal B.GetLength(0). Result size: rows A.GetLength(0), cols B.GetLength(1).
Allocate C
new int[rowsA, colsB] — elements start at 0.
Triple loop
For each (i,j), loop k and add A[i,k] * B[k,j] into C[i,j].
📜 Pseudocode
function multiply(A, B): // A is m×n, B is n×p
assert columns(A) = rows(B)
m ← rows(A)
n ← columns(A)
p ← columns(B)
C ← new matrix[m][p] filled with 0
for i from 0 to m - 1:
for j from 0 to p - 1:
for k from 0 to n - 1:
C[i][j] ← C[i][j] + A[i][k] * B[k][j]
return C 3×3 matrix multiplication (reference)
Classic interview solution: triple nested loops, sample matrices from the reference tutorial, full printout of A, B, and C.
using System;
class Program
{
static void MultiplyMatrices(int[,] firstMatrix, int[,] secondMatrix, int[,] resultMatrix)
{
int rowsFirst = firstMatrix.GetLength(0);
int colsFirst = firstMatrix.GetLength(1);
int colsSecond = secondMatrix.GetLength(1);
for (int i = 0; i < rowsFirst; i++)
{
for (int j = 0; j < colsSecond; j++)
{
for (int k = 0; k < colsFirst; k++)
{
resultMatrix[i, j] += firstMatrix[i, k] * secondMatrix[k, j];
}
}
}
}
static void DisplayMatrix(int[,] matrix)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine();
}
}
static void Main()
{
int[,] firstMatrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int[,] secondMatrix = {
{ 9, 8, 7 },
{ 6, 5, 4 },
{ 3, 2, 1 }
};
int[,] resultMatrix = new int[firstMatrix.GetLength(0), secondMatrix.GetLength(1)];
MultiplyMatrices(firstMatrix, secondMatrix, resultMatrix);
Console.WriteLine("First Matrix:");
DisplayMatrix(firstMatrix);
Console.WriteLine("\nSecond Matrix:");
DisplayMatrix(secondMatrix);
Console.WriteLine("\nResult Matrix:");
DisplayMatrix(resultMatrix);
}
} Explanation
resultMatrix is zero-initialized, so += accumulates each dot product. colsFirst is both the inner loop bound and the required row count of secondMatrix (3 here).
resultMatrix[i, j] += firstMatrix[i, k] * secondMatrix[k, j];Core line. Pair A[i,k] with B[k,j] — note the k index swaps between matrices.
2×2 multiplication with dimension check
Smaller matrices for hand-tracing, plus validation that inner dimensions align before multiplying.
using System;
class Program
{
static bool CanMultiply(int[,] a, int[,] b)
{
return a.GetLength(1) == b.GetLength(0);
}
static int[,] Multiply(int[,] a, int[,] b)
{
if (!CanMultiply(a, b))
{
throw new ArgumentException(
"Columns of A must equal rows of B.");
}
int rowsA = a.GetLength(0);
int colsA = a.GetLength(1);
int colsB = b.GetLength(1);
int[,] result = new int[rowsA, colsB];
for (int i = 0; i < rowsA; i++)
{
for (int j = 0; j < colsB; j++)
{
for (int k = 0; k < colsA; k++)
{
result[i, j] += a[i, k] * b[k, j];
}
}
}
return result;
}
static void DisplayMatrix(int[,] matrix)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
static void Main()
{
int[,] a = { { 1, 2 }, { 3, 4 } };
int[,] b = { { 5, 6 }, { 7, 8 } };
int[,] product = Multiply(a, b);
Console.WriteLine("A x B:");
DisplayMatrix(product);
}
} Explanation
C[0,0] = 1×5 + 2×7 = 19. Tracing one cell on paper before coding the loops helps avoid swapping k indices.
Beyond the basics
Return vs out parameter. Example 2 returns int[,]; Example 1 fills a pre-allocated array — both are common styles.
double[,] / jagged arrays. Same loop structure; jagged int[][] uses a[i].Length per row.
Interview: state dimensions first, write the triple loop, walk through one C[i,j] by hand, then mention O(mnp) time.
❓ FAQ
🔄 Input / output examples
Replace literal matrices in Main to experiment with other sizes that satisfy the dimension rule.
| Cell | Calculation | Result |
|---|---|---|
C[0,0] (3×3) | 1×9+2×6+3×3 | 30 |
C[0,1] (3×3) | 1×8+2×5+3×2 | 24 |
C[0,0] (2×2) | 1×5+2×7 | 19 |
C[1,1] (2×2) | 3×6+4×8 | 50 |
Edge cases and pitfalls
Most mistakes are wrong dimensions or swapped indices in the inner loop.
Inner mismatch
(2×3)×(2×2) is invalid — 3 ≠ 2. Check before allocating result.
B[k,j] not B[j,k]
Column j of B uses second index j; row k uses first index k.
Uninitialized sum
new int[,] is zero-filled — required for +=. Reusing an array? Clear it first.
AB vs BA
Swapping order usually changes the answer — not like addition.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
| Multiply (m×n)·(n×p) | O(m × n × p) | O(m × p) for result |
DisplayMatrix | O(rows × cols) | O(1) |
Naive triple-loop multiplication is the standard teaching approach; faster algorithms exist but are beyond intro scope.
Summary
- Rule: (m×n)·(n×p) → m×p; inner sizes must match.
- C#: loops
i, j, kwithC[i,j] += A[i,k] * B[k,j]. - Reference output: 3×3 result rows
30 24 18,84 69 54,138 114 90.
If A is m × n and B is n × p, the product C is m × p. The inner loop length n must match — columns of A equal rows of B. That is why matrix multiplication is not commutative: AB and BA may differ or be undefined.
6 people found this page helpful
