C Matrix Multiplication Program

Beginner
7 min read
Updated: Oct 2026
2 programs
Live preview

What Is Matrix Multiplication?

Matrix multiplication pairs each row of A with each column of B. If A is m × n and B is n × p, then AB exists and has size m × p.

Remember
A (m × n) × B (n × p) → C (m × p)

C[i][j] = sum over k of  A[i][k] * B[k][j]

Example (2×2):
  [1 2]   [5 6]   [1·5+2·7  1·6+2·8]   [19 22]
  [3 4] × [7 8] = [3·5+4·7  3·6+4·8] = [43 50]

Not the same as cell-by-cell multiply.
A shapeB shapeAllowed?Result
2 × 22 × 2Yes2 × 2
2 × 33 × 2Yes2 × 2
2 × 32 × 2No—

How to Multiply Matrices in C

Four clear steps — then code the classic triple loop.

  1. Check that A’s columns equal B’s rows.
  2. Create result C with size rowsA × colsB and zero it.
  3. For each i, j, accumulate sum += A[i][k] * B[k][j] over k.
  4. Store that sum in C[i][j].
MethodIdeaTimeBest for
Triple nested loopsDot product of row i and column jO(m × n × p)Interviews, teaching
Shape-safe multiplyValidate inner dimensions firstO(m × n × p)Safer production-style code

Pseudocode

Pseudocode
function Multiply(A, B):
    m = rows of A
    n = cols of A
    p = cols of B

    if n != rows of B:
        error "inner dimensions must match"

    C = new matrix[m][p]   // zeros
    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

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Shape rulecols(A) == rows(B)
Result sizerows(A) × cols(B)
Cell formulaΣ A[i][k] * B[k][j]
Loopsi rows, j cols, k shared
Not entrywiseDo not confuse with A[i][j] * B[i][j]
Classic check{{1,2},{3,4}} × {{5,6},{7,8}} = {{19,22},{43,50}}

Live Preview

Pick a sample pair to see A, B, and the product AB.

Tap a chip to run. Inner dimensions always match in these samples.

Result
A (2×2) =
1  2
3  4

B (2×2) =
5  6
7  8

A × B (2×2) =
19 22
43 50

Worked Walkthrough — 2×2

Each result cell is one row-column dot product.

Calculation
A = [1 2]    B = [5 6]
    [3 4]        [7 8]

C[0][0] = 1·5 + 2·7 = 5 + 14 = 19
C[0][1] = 1·6 + 2·8 = 6 + 16 = 22
C[1][0] = 3·5 + 4·7 = 15 + 28 = 43
C[1][1] = 3·6 + 4·8 = 18 + 32 = 50

Result = [19 22]
         [43 50]

C Programs

Start with the classic triple nested loop. Then add an inner-dimension check for safer code.

Example 1 — Triple Nested Loops

Accumulate each result cell as a row-column dot product.

C
#include <stdio.h>
#include <string.h>

#define N 2

void multiply(int a[N][N], int b[N][N], int c[N][N])
{
    int i, j, k;

    memset(c, 0, sizeof(int) * N * N);

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

void print_matrix(int m[N][N])
{
    int i, j;

    for (i = 0; i < N; i++)
    {
        for (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 c[N][N];

    multiply(a, b, c);
    print_matrix(c);
    return 0;
}

How It Works

  1. memset zeros the result — needed for a running sum with +=.
  2. Outer i picks the result row; middle j picks the result column.
  3. Inner k walks the shared dimension and adds a[i][k] * b[k][j].
  4. For C[0][0]: 1*5 + 2*7 = 19.
  5. Print walks the result one row per line.

Example 2 — Shape-Safe Multiply

Validate that A’s columns equal B’s rows before multiplying.

C
#include <stdio.h>
#include <string.h>

#define MAX 8

int multiply(int a[][MAX], int rows_a, int cols_a,
             int b[][MAX], int rows_b, int cols_b,
             int c[][MAX])
{
    int i, j, k;

    if (cols_a != rows_b)
    {
        printf("A columns (%d) must equal B rows (%d).\\n",
               cols_a, rows_b);
        return 0;
    }

    memset(c, 0, sizeof(int) * rows_a * MAX);

    for (i = 0; i < rows_a; i++)
    {
        for (j = 0; j < cols_b; j++)
        {
            for (k = 0; k < cols_a; k++)
            {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    return 1;
}

int main(void)
{
    int a[2][MAX] = { { 1, 2, 3 }, { 4, 5, 6 } };      /* 2×3 */
    int b[3][MAX] = { { 7, 8 }, { 9, 10 }, { 11, 12 } }; /* 3×2 */
    int c[2][MAX];
    int i, j;

    if (!multiply(a, 2, 3, b, 3, 2, c))
    {
        return 1;
    }

    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 2; j++)
        {
            printf("%d ", c[i][j]);
        }
        printf("\\n");
    }
    return 0;
}

How It Works

  1. Compare cols_a with rows_b.
  2. Return early if inner dimensions differ — multiplication is undefined.
  3. Result size is 2 × 2 for a 2×3 times a 3×2.
  4. Same triple loop accumulates each cell after zeroing.
  5. Check: C[0][0] = 1·7 + 2·9 + 3·11 = 58.

Edge Cases & Pitfalls

Check these before calling the solution done.

Inner dims

Must match

cols(A) == rows(B) or the product is undefined.

Entrywise

Wrong algorithm

Do not write A[i][j] * B[i][j] for true matrix multiply.

Order

AB ≠ BA

Multiplication is not commutative in general.

Overflow

Use long long when needed

Products and sums can exceed INT_MAX.

Time and Space Complexity

ProgramTimeExtra space
Triple loopsO(m × n × p)O(1) besides result
Shape-safe multiplyO(m × n × p)O(1) besides result

For square n × n matrices the classic algorithm is O(n³). The result needs O(m × p) space.

Key Takeaways

  • Rule: cols(A) == rows(B); result is rows(A) × cols(B).
  • Cell: C[i][j] = Σ A[i][k] * B[k][j].
  • Loops: three levels — i, j, then k.
  • Test: {{1,2},{3,4}} × {{5,6},{7,8}} → {{19,22},{43,50}}.

One line: each result cell is the dot product of a row of A and a column of B.

Frequently Asked Questions

A’s column count must equal B’s row count. If A is m × n and B is n × p, then AB is m × p.
No. Matrix multiplication uses row-column dot products. Cell-by-cell multiply is a different operation (Hadamard).
One loop picks result row i, one picks column j, and the inner loop accumulates sum over k of A[i][k] * B[k][j].
Not in general. Matrix multiplication is not commutative — AB and BA can differ, and one order may be undefined.
For an m × n matrix times an n × p matrix, classic triple loops cost O(m × n × p). For square n × n matrices that is O(n³).

Next: Matrix Subtraction

Subtract matching cells of two same-sized matrices.

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.

10 people found this page helpful