Perform Matrix Multiplication in C

Beginner
⏱️ 12 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
Linear algebra

What You’ll Learn

Matrix multiplication combines rows of A with columns of B via dot products — not cell-by-cell products. This tutorial covers the dimension rule, the triple nested loop, zero-initialization, a live preview, worked C examples (3×3 and 2×2), edge cases, and O(n³) complexity.

Rule

Row × Col

Each Cij is a dot product of row i of A with column j of B.

Inner Sizes

(m×n)(n×p)

Columns of A must equal rows of B; product is m × p.

Triple Loop

i, j, k

Outer result indices, inner shared dimension for the sum.

Zero First

result = 0

Clear the output before accumulating with +=.

Live Preview

3×3 AB

See both factors and the product instantly.

Not Hadamard

≠ Aij*Bij

Element-wise multiply is a different operation.

Introduction

If A is m × n and B is n × p, then matrix multiplication produces C = AB of shape m × p, where each entry is Cij = ∑k Aik Bkj.

In C interviews you write three nested loops, zero the result first, and contrast this with addition or element-wise multiply.

Why it matters?

It is the classic 2D-array interview problem: dimension rules, triple loops, and accumulation — skills that underpin graphics, ML kernels, and linear-algebra libraries.

Key Highlights

Dot Products

Each output cell is one row·column sum.

Match Inner n

A cols must equal B rows.

Zero Then +=

Clear result before accumulating products.

O(n³)

Classic cost for square n×n factors.

In short: zero C, then for each i,j accumulate C[i][j] += A[i][k] * B[k][j] over the shared dimension k.

📝 Problem & Approach

Given compatible matrices A and B, compute C = AB using the row–column rule and print the factors plus the product.

c
/* A 3×3, B 3×3 → C 3×3
 * C[0][0] = 1*9 + 2*6 + 3*3 = 30
 * C[i][j] = sum_k A[i][k] * B[k][j]
 */

Inputs & Outputs

ItemTypeDescription
a, b2D arraysFactors; for square samples, both are N × N.
result2D arrayProduct; must be zeroed before accumulation.
NmacroSquare size (3 or 2 in the examples).

Minimal workflow

Pseudocode
function multiply(A, B, C, n):   // n×n matrices
    for i from 0 to n - 1:
        for j from 0 to n - 1:
            C[i][j] ← 0
            for k from 0 to n - 1:
                C[i][j] ← C[i][j] + A[i][k] * B[k][j]

Method comparison

OperationRuleLoops
Matrix multiply (this page)Row·column sumsTriple nest
Element-wise / HadamardAij * BijDouble nest; same shape
AdditionAij + BijDouble nest; same shape

⚡ Quick Reference

GoalPattern
Zero cellresult[i][j] = 0;
Accumulateresult[i][j] += a[i][k] * b[k][j];
Shared indexk walks A’s columns / B’s rows
Compatibilitycols(A) == rows(B)
Square costO(n³) for n × n

📋 Multiply vs Add vs Element-wise *

Related matrix operations — only true multiplication uses the shared-dimension k loop.

AB product
Σ Aik Bkj

This page — row times column

Addition
Aij+Bij

Same shape; no k loop

Hadamard
Aij*Bij

Same shape; element-wise only

Interview tip
zero first

Always clear result before +=

Context

When This Problem Shows Up

Reach for matrix multiplication when composing linear maps or combining grids by rows and columns.

  1. Interview staple

    Tests 2D indexing, triple loops, and dimension awareness.

  2. Graphics / transforms

    Composing transformation matrices.

  3. ML / dense layers

    Weight matrices times activations (conceptually).

  4. Contrast with Hadamard

    Clarify when the prompt wants true product vs element-wise.

  5. Not for mismatched inner sizes

    Refuse when columns of A ≠ rows of B.

Key benefit: one algorithm that proves you understand both the algebra and the nested-loop implementation details.

🔮 Live Preview

Uses the same 3×3 integer matrices as Example 1. Press the button to print both factors and AB.

Integer arithmetic in JavaScript; matches the C sample.

Live result
Press “Show 3×3 product”.

Examples Gallery

Two complete C programs — a classic 3×3 product and a smaller 2×2 you can check by hand. Click View Output to reveal sample console results.

📚 Getting Started

Zero the result, then accumulate with three nested loops.

Example 1 — Multiply Two 3×3 Matrices

Same matrices and output pattern as the classic walkthrough: multiply_matrices fills the result; display_matrix prints with tabs.

c
#include <stdio.h>

#define N 3

void multiply_matrices(int a[N][N], int b[N][N], int result[N][N]) {
    int i, j, k;

    for (i = 0; i < N; ++i) {
        for (j = 0; j < N; ++j) {
            result[i][j] = 0;
        }
    }

    for (i = 0; i < N; ++i) {
        for (j = 0; j < N; ++j) {
            for (k = 0; k < N; ++k) {
                result[i][j] += a[i][k] * b[k][j];
            }
        }
    }
}

void display_matrix(int matrix[N][N]) {
    int i, j;

    for (i = 0; i < N; ++i) {
        for (j = 0; j < N; ++j) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    int first_matrix[N][N] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int second_matrix[N][N] = {
        {9, 8, 7},
        {6, 5, 4},
        {3, 2, 1}
    };
    int result[N][N];

    multiply_matrices(first_matrix, second_matrix, result);

    printf("First Matrix:\n");
    display_matrix(first_matrix);

    printf("\nSecond Matrix:\n");
    display_matrix(second_matrix);

    printf("\nResult Matrix:\n");
    display_matrix(result);

    return 0;
}

How It Works

The innermost index k pairs a[i][k] with b[k][j]. Initializing result to zero matters because each result[i][j] is a sum of products.

📈 Practical Patterns

Same triple-loop pattern with a size you can verify on paper.

Example 2 — Smaller 2×2 Product

Top-left output is 1·5 + 2·7 = 19. Zero-init is combined with the k loop in one nest.

c
#include <stdio.h>

#define N 2

void multiply_matrices(int a[N][N], int b[N][N], int result[N][N]) {
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            result[i][j] = 0;
            for (int k = 0; k < N; ++k) {
                result[i][j] += a[i][k] * b[k][j];
            }
        }
    }
}

void display_matrix(const char *title, int m[N][N]) {
    printf("%s\n", title);
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            printf("%d ", m[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    int a[N][N] = {
        {1, 2},
        {3, 4}
    };
    int b[N][N] = {
        {5, 6},
        {7, 8}
    };
    int r[N][N];

    multiply_matrices(a, b, r);

    display_matrix("A", a);
    printf("\n");
    display_matrix("B", b);
    printf("\n");
    display_matrix("AB", r);

    return 0;
}

How It Works

Combining zero-init with the k loop in one nest is a compact variant; mathematically it matches Example 1.

🧠 How the Algorithm Multiplies Matrices

1

Check compatibility

Confirm columns of A equal rows of B (fixed N in the samples).

Shape
2

Zero the output

Set every result[i][j] to 0 before accumulating.

Init
3

Triple loop

For each i, j, add A[i][k]*B[k][j] for all k.

Accumulate
=

Product ready

For the 3×3 sample, top-left is 30; full result matches the printed table.

🔎 Worked Walkthrough — Top-Left of the 3×3 Sample

Trace C[0][0]: row 0 of A dotted with column 0 of B.

kA[0][k]B[k][0]ProductRunning sum
01999
1261221
233930

So C[0][0] = 30. Repeat the same pattern for every other (i, j).

Use Cases

Where matrix-multiplication thinking shows up beyond the interview prompt.

1. Triple-Loop Practice

Master nested control flow and shared indices.

Example: i, j, then k.

2. Linear Transforms

Compose rotations, scales, and projections.

Example: graphics pipelines.

3. Complexity Discussion

Lead into O(n³) and blocked algorithms.

Example: interview follow-ups on speed.

4. Contrast Element-wise Ops

Show why addition/division pages use different loops.

Example: previous matrix tutorials.

5. Non-Commutativity

AB ≠ BA in general — a favorite quiz point.

Example: swap factors and recompute.

6. Overflow Awareness

Products of ints can overflow before the final sum.

Example: suggest long long when needed.

Pro Tip: state the dimension rule and zero-init out loud before writing the triple loop.

Advantages

Why this approach earns interview points.

  1. 1. Matches the Definition

    Code mirrors the sum-of-products formula one-for-one.

  2. 2. Easy to Generalize

    Change bounds for rectangular m×n by n×p.

  3. 3. Clear Complexity Story

    O(n³) is the expected answer for square classic code.

  4. 4. Hand-Checkable

    2×2 and one cell of 3×3 dry-run cleanly on a whiteboard.

Pro Tip: mention blocked / tiled multiply only as a follow-up after the correct triple loop.

Usage Tips

Small habits that keep matrix-multiplication code clean in interviews.

  1. 1. State Inner Dimensions First

    Say (m×n)(n×p) → m×p before coding.

  2. 2. Always Zero the Result

    Garbage in result ruins every += sum.

  3. 3. Keep k as the Shared Index

    Write a[i][k] * b[k][j] — not swapped.

  4. 4. Dry-Run One Cell

    Compute C[0][0] on paper before trusting the full nest.

  5. 5. Mention Overflow

    Suggest long long when entries or n grow large.

Pro Tip: the walkthrough table for C[0][0] is the fastest way to lock in the k loop before typing.

Common Pitfalls

Mistakes that commonly break matrix-multiplication solutions in C.

  1. 1. Skipping Zero Initialization

    Uninitialized result makes += start from garbage.

    → Set every cell to 0 before the k loop.

  2. 2. Writing Element-wise Multiply

    C[i][j] = A[i][j] * B[i][j] is Hadamard, not AB.

    → Use the shared k sum of products.

  3. 3. Swapping Indices on B

    Using b[j][k] instead of b[k][j] flips columns.

    → Memorize a[i][k] * b[k][j].

  4. 4. Ignoring Inner Dimensions

    Multiplying incompatible shapes is undefined.

    → Require cols(A) == rows(B).

  5. 5. Assuming AB = BA

    Order matters for matrices.

    → Keep left and right factors in the intended order.

Edge Cases

Rules that trip beginners — check these before calling the solution done.

Shape

Inner dimensions

You cannot multiply m×n by p×q unless n = p.

Order

AB vs BA

Matrix multiplication is not commutative in general.

Overflow

Integer products

Intermediate products may overflow int; consider wider types.

Init

Unzeroed result

Always clear the output buffer before +=.

1×n

Vectors

Row or column vectors still follow the same dimension rule.

Identity

I factor

Multiplying by the identity leaves the other matrix unchanged — good sanity check.

🔄 Input / Output

Examples use literals in main. To accept typed input, add nested scanf loops and verify dimensions before multiplying.

SampleResult highlight
3×3 demoTop-left of AB is 30; full matrix as printed
2×2 demoAB = [[19, 22], [43, 50]]

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Trace C[1][2] by hand

  • Use the 3×3 sample factors
  • Confirm it equals 54

2. Swap A and B

  • Compute BA for the 2×2 sample
  • Show it differs from AB

3. Rectangular multiply

  • Multiply a 2×3 by a 3×2
  • Generalize loop bounds

4. Identity check

  • Multiply A by I and verify A
  • Good unit-test style drill

Notes

  • Rule. Cij = sumk AikBkj; inner sizes of A and B must match.
  • Zero result, then three nested loops with += a[i][k]*b[k][j].
  • Complexity is cubic in n for square n×n matrices.
  • Not the same as element-wise (Hadamard) multiplication.

Quick Takeaway: match inner dimensions, zero the result, then accumulate a[i][k]*b[k][j] for every output cell.

⏱️ Time and Space Complexity

SettingTimeExtra space
Two n × n matrices, classic triple loopO(n3)O(1) beyond outputs
m×n by n×pO(m · n · p)O(1) beyond outputs
Wrap Up

🎉 Conclusion

Matrix multiplication is the step up from addition: match the shared dimension, zero the result, and run three nested loops that accumulate row·column products. Master the 3×3 and 2×2 samples so you can generalize sizes on demand.

Practice both examples above, then continue to matrix subtraction for another element-wise warm-up.

Zero C, then C[i][j] += A[i][k] * B[k][j] for all i, j, k — with matching inner sizes.

💡 Best Practices

✅ Do

  • State the (m×n)(n×p) rule before coding
  • Zero the result before accumulating
  • Use a[i][k] * b[k][j] consistently
  • Dry-run one output cell by hand
  • Quote O(n³) for square classic loops

❌ Don’t

  • Confuse AB with element-wise multiply
  • Skip zeroing the result buffer
  • Multiply incompatible shapes
  • Assume AB equals BA
  • Ignore possible int overflow

Key Takeaways

Knowledge Unlocked

Five things to remember about matrix multiplication in C

Implement it the interview-friendly way.

5
Core concepts
n 02

Inner n

Must match

Shape
3 03

Loops

i, j, k

Code
0 04

Zero

Then +=

Init
O 05

Cost

O(n³)

Analysis

❓ Frequently Asked Questions

The number of columns of A must equal the number of rows of B. If A is m×n and B is n×p, the product AB exists and is m×p. If those inner sizes differ, multiplication is not defined this way.
No. Element-wise multiplication (Hadamard product) only works for same-shaped matrices and multiplies matching entries. Standard matrix multiplication uses the row-column dot-product rule shown on this page.
Typical order: i loops rows of the result, j loops columns of the result, k walks along the shared dimension to accumulate sum_k A[i][k]*B[k][j]. Some codes reorder loops for cache performance, but the math is the same.
Because each result entry is built as a running sum: result[i][j] += ... You must start from zero before adding products.
Products and sums can exceed int range for large entries or sizes. Use wider types (long long) or floating types when the problem demands it.
The classic triple loop does Θ(n³) arithmetic operations for square n×n matrices. Space aside from inputs/output is O(1) extra if you only store a few loop variables.
Not in general. Matrix multiplication is not commutative: AB and BA can differ even when both products exist.
Generalize loop bounds: i < rowsA, j < colsB, k < colsA (must equal rowsB). The product shape is rowsA × colsB.

Did you Know? 🔊

Matrix multiplication links rows of A with columns of B. You need A to be m × n and B to be n × p—the two n’s must match—then AB is m × p.

Continue to Matrix Subtraction

Learn how to subtract two matrices element-wise with 2D arrays in C.

Matrix Subtraction tutorial →

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.

8 people found this page helpful