0
0
CProgramBeginner · 2 min read

C Program to Multiply Two Matrices with Output

To multiply two matrices in C, use nested loops to calculate the sum of products of corresponding elements, like result[i][j] += matrix1[i][k] * matrix2[k][j] inside three loops iterating over rows and columns.
📋

Examples

InputMatrix1: [[1, 2], [3, 4]] Matrix2: [[5, 6], [7, 8]]
OutputResult: [[19, 22], [43, 50]]
InputMatrix1: [[2, 0], [1, 3]] Matrix2: [[1, 4], [2, 5]]
OutputResult: [[2, 8], [7, 19]]
InputMatrix1: [[0, 0], [0, 0]] Matrix2: [[1, 2], [3, 4]]
OutputResult: [[0, 0], [0, 0]]
🧠

How to Think About It

To multiply two matrices, think of each element in the result as the sum of multiplying elements from a row of the first matrix with elements from a column of the second matrix. You use three loops: one for rows of the first matrix, one for columns of the second, and one to multiply and sum the matching elements.
📐

Algorithm

1
Get the number of rows and columns for both matrices.
2
Check if multiplication is possible (columns of first == rows of second).
3
Create a result matrix with rows of first and columns of second.
4
For each row in first matrix, and each column in second matrix:
5
Calculate the sum of products of corresponding elements and store in result.
6
Print the result matrix.
💻

Code

c
#include <stdio.h>
int main() {
    int r1 = 2, c1 = 2, r2 = 2, c2 = 2;
    int matrix1[2][2] = {{1, 2}, {3, 4}};
    int matrix2[2][2] = {{5, 6}, {7, 8}};
    int result[2][2] = {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] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }

    printf("Result:\n");
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }
    return 0;
}
Output
Result: 19 22 43 50
🔍

Dry Run

Let's trace multiplying matrix1 [[1, 2], [3, 4]] and matrix2 [[5, 6], [7, 8]] through the code.

1

Initialize result matrix

result = [[0, 0], [0, 0]]

2

Calculate result[0][0]

result[0][0] = (1*5) + (2*7) = 5 + 14 = 19

3

Calculate result[0][1]

result[0][1] = (1*6) + (2*8) = 6 + 16 = 22

4

Calculate result[1][0]

result[1][0] = (3*5) + (4*7) = 15 + 28 = 43

5

Calculate result[1][1]

result[1][1] = (3*6) + (4*8) = 18 + 32 = 50

ElementCalculationValue
result[0][0]1*5 + 2*719
result[0][1]1*6 + 2*822
result[1][0]3*5 + 4*743
result[1][1]3*6 + 4*850
💡

Why This Works

Step 1: Matrix multiplication rule

Each element in the result matrix is the sum of products of elements from a row of the first matrix and a column of the second matrix using result[i][j] += matrix1[i][k] * matrix2[k][j].

Step 2: Use of three loops

The outer two loops select the position in the result matrix, and the inner loop calculates the sum of products for that position.

Step 3: Initialization of result matrix

The result matrix is initialized to zero to accumulate sums correctly without garbage values.

🔄

Alternative Approaches

Dynamic input with user prompts
c
#include <stdio.h>
int main() {
    int r1, c1, r2, c2;
    printf("Enter rows and columns of first matrix: ");
    scanf("%d %d", &r1, &c1);
    printf("Enter rows and columns of second matrix: ");
    scanf("%d %d", &r2, &c2);
    if (c1 != r2) {
        printf("Multiplication not possible\n");
        return 0;
    }
    int matrix1[r1][c1], matrix2[r2][c2], result[r1][c2];
    for (int i = 0; i < r1; i++)
        for (int j = 0; j < c1; j++)
            scanf("%d", &matrix1[i][j]);
    for (int i = 0; i < r2; i++)
        for (int j = 0; j < c2; j++)
            scanf("%d", &matrix2[i][j]);
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            result[i][j] = 0;
            for (int k = 0; k < c1; k++)
                result[i][j] += matrix1[i][k] * matrix2[k][j];
        }
    }
    printf("Result:\n");
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++)
            printf("%d ", result[i][j]);
        printf("\n");
    }
    return 0;
}
Allows user to input any size matrices but requires validation and more code.
Using functions for multiplication
c
#include <stdio.h>
void multiply(int r1, int c1, int r2, int c2, int m1[r1][c1], int m2[r2][c2], int res[r1][c2]) {
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            res[i][j] = 0;
            for (int k = 0; k < c1; k++)
                res[i][j] += m1[i][k] * m2[k][j];
        }
    }
}
int main() {
    int m1[2][2] = {{1, 2}, {3, 4}};
    int m2[2][2] = {{5, 6}, {7, 8}};
    int res[2][2];
    multiply(2, 2, 2, 2, m1, m2, res);
    printf("Result:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++)
            printf("%d ", res[i][j]);
        printf("\n");
    }
    return 0;
}
Separates multiplication logic into a function for cleaner code and reuse.

Complexity: O(r1 * c2 * c1) time, O(r1 * c2) space

Time Complexity

The program uses three nested loops: outer loops over rows of first matrix and columns of second matrix, and inner loop over columns of first matrix, resulting in O(r1 * c2 * c1).

Space Complexity

The result matrix requires space proportional to the product of rows of first and columns of second matrix, O(r1 * c2).

Which Approach is Fastest?

All approaches have similar time complexity; using functions improves readability but not speed. Dynamic input adds flexibility but no speed gain.

ApproachTimeSpaceBest For
Fixed-size arraysO(r1*c2*c1)O(r1*c2)Simple, fixed matrices
Dynamic inputO(r1*c2*c1)O(r1*c2)User input, flexible sizes
Function-basedO(r1*c2*c1)O(r1*c2)Code reuse and clarity
💡
Always check if the number of columns in the first matrix equals the number of rows in the second before multiplying.
⚠️
Beginners often forget to initialize the result matrix to zero, causing incorrect sums.