Skip to content
Devtoolry

Arrays and algorithms · intermediate

C Program to Multiply Two Matrices

Multiply two matrices in C with 2D arrays and three nested loops, check the dimensions first, and print the result with aligned columns.

Two matrices can be multiplied when the first has as many columns as the second has rows. Each cell of the result is the dot product of a row of the first matrix and a column of the second, which in C becomes three nested loops over 2D arrays.

The program

C
#include <stdio.h>

#define R1 2
#define C1 3
#define C2 2

int main(void) {
    int a[R1][C1] = {{1, 2, 3}, {4, 5, 6}};
    int b[C1][C2] = {{7, 8}, {9, 10}, {11, 12}};
    int result[R1][C2] = {{0}};

    for (int i = 0; i < R1; i++)
        for (int j = 0; j < C2; j++)
            for (int k = 0; k < C1; k++)
                result[i][j] += a[i][k] * b[k][j];

    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++)
            printf("%5d", result[i][j]);
        printf("\n");
    }
    return 0;
}
Output
   58   64
  139  154

How it works

  1. a is 2 × 3 and b is 3 × 2, so the product is 2 × 2: the inner dimensions (3) match.
  2. result is initialized to zeros with {{0}}, because each cell is built up with +=.
  3. For cell (i, j), the k loop adds a[i][k] × b[k][j] over the shared dimension: 1×7 + 2×9 + 3×11 = 58.
  4. %5d prints each number right-aligned in 5 characters, so the columns line up.

Another way: Matrix addition

Adding matrices is simpler: both must have the same size, and each cell is the sum of the matching cells.

C
#include <stdio.h>

int main(void) {
    int a[2][2] = {{1, 2}, {3, 4}};
    int b[2][2] = {{5, 6}, {7, 8}};
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++)
            printf("%4d", a[i][j] + b[i][j]);
        printf("\n");
    }
    return 0;
}
Output
   6   8
  10  12

Common mistakes

  • Not initializing result: its cells then start with garbage values before +=.
  • Multiplying cell by cell (a[i][j] * b[i][j]): that is the element-wise product, not matrix multiplication.
  • Mixing up the loop bounds, for example running k to C2 instead of C1.

Try it yourself

  • Read both matrices with scanf, and refuse to multiply when the dimensions do not match.
  • Print the transpose of a matrix.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.