C PROGRAMMING PROGRAM • MATRICES

Multiply Two Matrices

Learn how to multiply two matrices using a clear C program.

Advanced2D arraysMatrix multiplicationTriple loop

PROBLEM UNDERSTANDING

Input and expected output

Sample input
2 3
3 2
1 2 3
4 5 6
7 8
9 10
11 12
Sample output
58 64
139 154

COMPLETE C PROGRAM

Complete C implementation

matrix-multiplication.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int firstRows, firstColumns, secondRows, secondColumns;
    int first[10][10], second[10][10], product[10][10] = {0};

    scanf("%d %d", &firstRows, &firstColumns);
    scanf("%d %d", &secondRows, &secondColumns);
    if (firstRows < 1 || firstRows > 10 || firstColumns < 1 || firstColumns > 10 ||
        secondRows < 1 || secondRows > 10 || secondColumns < 1 || secondColumns > 10 ||
        firstColumns != secondRows) {
        printf("Matrices cannot be multiplied.\n");
        return 0;
    }
    for (int row = 0; row < firstRows; row++)
        for (int column = 0; column < firstColumns; column++) scanf("%d", &first[row][column]);
    for (int row = 0; row < secondRows; row++)
        for (int column = 0; column < secondColumns; column++) scanf("%d", &second[row][column]);
    for (int row = 0; row < firstRows; row++)
        for (int column = 0; column < secondColumns; column++)
            for (int index = 0; index < firstColumns; index++)
                product[row][column] += first[row][index] * second[index][column];
    for (int row = 0; row < firstRows; row++) {
        for (int column = 0; column < secondColumns; column++) printf("%d ", product[row][column]);
        printf("\n");
    }
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

58 64
139 154
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. For each result cell, calculate the dot product of one row and one column.
  3. Display the computed result.

For each result cell, calculate the dot product of one row and one column.

EFFICIENCY

Time and space complexity

Time complexity

O(r₁ × c₁ × c₂)

Auxiliary space

O(rows × columns)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.