C Program to Compute Matrix Multiplication Using Multi-dimensional Arrays

1. Introduction

Matrix multiplication is a foundational operation in linear algebra and is crucial in numerous applications, ranging from physics to graphics processing. In C, multi-dimensional arrays, especially two-dimensional arrays, are the perfect tool for matrix operations. This tutorial introduces a C program that multiplies two matrices using two-dimensional arrays.

2. Program Overview

1. Declare two two-dimensional arrays (matrices) and a third one to store the result.

2. Use nested loops to traverse through each element of the matrices.

3. For each element in the result matrix, perform a dot product of the corresponding row of the first matrix with the column of the second matrix.

4. Display the resultant matrix.

3. Code Program

#include <stdio.h>

int main() {
    int matrix1[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    int matrix2[3][3] = {
        {9, 8, 7},
        {6, 5, 4},
        {3, 2, 1}
    };

    int result[3][3];
    int i, j, k;

    // Initialize the result matrix to zeros
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            result[i][j] = 0;
        }
    }

    // Matrix multiplication
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            for(k = 0; k < 3; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }

    // Printing the resultant matrix
    printf("Resultant Matrix:\n");
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output:

Resultant Matrix:
30 24 18
84 69 54
138 114 90

4. Step By Step Explanation

1. We start by defining two matrices, matrix1 and matrix2, of size 3x3 with pre-defined values.

2. A matrix named result is also declared to store the product of the two matrices.

3. The result matrix is initialized to zeros using a nested loop structure.

4. Nested loops (3 layers) are then used for the matrix multiplication. The outer two loops traverse through the rows and columns of the result matrix, while the innermost loop (index k) performs the dot product operation.

5. The dot product for the element at the (i,j) position in the result matrix involves summing the products of elements from the ith row of matrix1 and the jth column of matrix2.

6. After computing the entire matrix product, another set of nested loops is used to print out the resultant matrix.

Comments