C Program for Matrix Multiplication

Subject: PPS (Programming for Problem Solving)

Contributed By: Sanjay

Created At: February 3, 2025

Question:


Write a C Program for Matrix Multiplication

Explanation Video:

Custom Image

Explanation:

 

Matrix multiplication follows row-column multiplication rules. The number of columns in the first matrix should be equal to the number of rows in the second matrix. The result matrix will have dimensions (rows of first matrix) × (columns of second matrix).

Explanation:

  1. Matrix A is 2×3 (2 rows, 3 columns) and matrix B is 3×2 (3 rows, 2 columns).

  2. The result matrix will be 2×2 because the number of rows of A is taken, and the number of columns of B is taken.

  3.  The triple for loop iterates over rows of A, columns of B, and sums up element-wise multiplications for each row-column pair

Source Code:
#include <stdio.h>

int main() {
    int A[2][3] = {{1, 2, 3}, {4, 5, 6}};  // First matrix (2x3)
    int B[3][2] = {{7, 8}, {9, 10}, {11, 12}}; // Second matrix (3x2)
    int result[2][2] = {0}; // Result matrix (2x2)
    
    // Matrix multiplication logic
    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];
            }
        }
    }

    // Display the result matrix
    printf("Product of matrices:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Output:
Product of matrices:
58  64
139 154
Share this Article & Support Us:
Status
printf('Loading...');