C Matrix Multiplication Program

To multiply matrix A (r1 x c1) with matrix B (c1 x c2), the number of columns of A must be equal to the number of rows of B. The result has r1 rows and c2 columns. Each element is the sum of the products of a row of A and a column of B.

#include <stdio.h>

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

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

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

Output:

Output of the above program is

58 64
139 154

How it works

  • The first element is 1*7 + 2*9 + 3*11 = 58.
  • The loop i goes through the rows of A, j through the columns of B, and k adds the products.
  • The result matrix must start with zeros, because we use +=.
Note: The time taken is proportional to r1 x c2 x c1, so it grows fast for big matrices. Related: Two Dimensional Arrays and Nested Loops.

Learn more about the similar topics:
Tutorials
C Arrays
C Two Dimensional Arrays
C Passing Arrays to Functions
C Strings
C String Input and Output
C String Functions
C strlen() Function
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?