Perform Matrix Multiplication in C#

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
Triple nested loops

What you’ll learn

  • The dimension rule: multiply m×n by n×p to get m×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 for loops (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.

(m×n)(n×p) m×p
C[0,0] row0·col0
AB vs BA often different

Formal definition

Cij = Σk=0n-1 Aik × Bkj where n is the column count of A (and row count of B).

Sample top-left cell

1×9 + 2×6 + 3×3 = 30 for the reference 3×3 matrices.

Quick examples

Row 0 30 24 18
From
3×3 reference
2×2 19 22
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.

Matrix A

Matrix B

Default product top row: 19 22.

Live result
Press “Multiply matrices” to compute A × B.

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

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
1

3×3 matrix multiplication (reference)

Classic interview solution: triple nested loops, sample matrices from the reference tutorial, full printout of A, B, and C.

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×2 multiplication with dimension check

Smaller matrices for hand-tracing, plus validation that inner dimensions align before multiplying.

c#
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

When the number of columns in the first matrix equals the number of rows in the second. If A is m×n and B is n×p, the product C is m×p.
Outer i walks rows of A, middle j walks columns of B, inner k multiplies A[i,k] by B[k,j] and adds into C[i,j] — a dot product of row i with column j.
30. Row 0 of A dotted with column 0 of B: 1×9 + 2×6 + 3×3 = 30.
No. A×B and B×A are generally different, and one may be undefined if dimensions do not align.
Each C[i,j] accumulates products from k = 0 to n−1. A new int[,] is zero-initialized in C#, so += builds the sum correctly.
Element-wise multiplies matching cells (like division on the previous page). True matrix multiply combines entire rows and columns.
O(m × n × p) — three nested loops over those dimensions.

🔄 Input / output examples

Replace literal matrices in Main to experiment with other sizes that satisfy the dimension rule.

CellCalculationResult
C[0,0] (3×3)1×9+2×6+3×330
C[0,1] (3×3)1×8+2×5+3×224
C[0,0] (2×2)1×5+2×719
C[1,1] (2×2)3×6+4×850

Edge cases and pitfalls

Most mistakes are wrong dimensions or swapped indices in the inner loop.

Size

Inner mismatch

(2×3)×(2×2) is invalid — 3 ≠ 2. Check before allocating result.

Index

B[k,j] not B[j,k]

Column j of B uses second index j; row k uses first index k.

Zero

Uninitialized sum

new int[,] is zero-filled — required for +=. Reusing an array? Clear it first.

Order

AB vs BA

Swapping order usually changes the answer — not like addition.

⏱️ Time and space complexity

OperationTimeExtra space
Multiply (m×n)·(n×p)O(m × n × p)O(m × p) for result
DisplayMatrixO(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, k with C[i,j] += A[i,k] * B[k,j].
  • Reference output: 3×3 result rows 30 24 18, 84 69 54, 138 114 90.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful