C Program to Multiply Two Matrices by Passing Matrix to a Function

Multiplying two matrices is a common operation in linear algebra and computational mathematics. In this article, we will explore how to write a C Program to Multiply Two Matrices by Passing Matrix to a Function.

Prerequisites

Before delving into the code, ensure you have the following prerequisites:

  • Basic understanding of C programming.
  • Familiarity with arrays, functions, and loops in C.
  • A C compiler installed on your system (e.g., GCC).

Simple Iterative Approach to Multiply Two Matrices by Passing Matrix to a Function

1.1 Explanation

In this approach, we will create a function to perform matrix multiplication. The function will accept two matrices as parameters and return the resulting matrix after multiplication.

1.2 Program

C
#include <stdio.h>

void multiplyMatrices(int mat1[10][10], int mat2[10][10], int res[10][10], int rows1, int cols1, int cols2) {
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols2; j++) {
            res[i][j] = 0;
            for (int k = 0; k < cols1; k++) {
                res[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}

void displayMatrix(int matrix[10][10], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int mat1[10][10], mat2[10][10], result[10][10];
    int rows1, cols1, rows2, cols2;

    printf("Enter the number of rows and columns for matrix 1: ");
    scanf("%d %d", &rows1, &cols1);
    printf("Enter the number of rows and columns for matrix 2: ");
    scanf("%d %d", &rows2, &cols2);

    if (cols1 != rows2) {
        printf("Invalid dimensions for matrix multiplication.\n");
        return 1;
    }

    printf("Enter elements of matrix 1:\n");
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols1; j++) {
            scanf("%d", &mat1[i][j]);
        }
    }

    printf("Enter elements of matrix 2:\n");
    for (int i = 0; i < rows2; i++) {
        for (int j = 0; j < cols2; j++) {
            scanf("%d", &mat2[i][j]);
        }
    }

    multiplyMatrices(mat1, mat2, result, rows1, cols1, cols2);

    printf("Product of the matrices:\n");
    displayMatrix(result, rows1, cols2);

    return 0;
}

1.3 Output

C
Enter the number of rows and columns for matrix 1: 2 3
Enter the number of rows and columns for matrix 2: 3 2
Enter elements of matrix 1:
1 2 3
4 5 6
Enter elements of matrix 2:
7 8
9 10
11 12
Product of the matrices:
58 64
139 154

Conclusion

Multiplying matrices is a fundamental operation in linear algebra and implementing it in C requires an understanding of arrays, loops, and functions. Simple Iterative Approach uses fixed-size arrays and is suitable for small matrices with known dimensions at compile time. However, it may not be efficient for large matrices due to memory limitations.