• Articles
  • Tutorials
  • Interview Questions

How to Write C Program for Matrix Multiplication

Understanding matrix multiplication is essential because it is at the core of many mathematical and computational applications. We’ll clarify the mystery related to matrix multiplication in this blog by examining its complexities in the context of the C programming language.

Table of Contents

Explore the world of C programming with this captivating YouTube video—your gateway to a comprehensive learning experience!

Introduction to Matrix Multiplication in C

Matrix multiplication is a fundamental operation in linear algebra, a branch of mathematics that deals with vector spaces and linear mappings between them. Matrices are rectangular arrays of numbers, symbols, or expressions arranged in rows and columns. Multiplying matrices involves combining elements in a systematic way to produce a new matrix.

Let’s consider two matrices, A and B, where A has dimensions m x n (m rows and n columns) and B has dimensions n x p (n rows and p columns). The resulting matrix C, obtained by multiplying A and B, will have dimensions of m x p.

Matrix Representation

Matrices are rectangular arrays of numbers, arranged in rows and columns. 

For example,

Matrix A: m × n matrix (m rows, n columns)

Matrix B: n × p matrix (n rows, p columns)

Multiplication Process

Refer to the below image to understand the concept of matrix multiplication clearly.

Multiplication of Two Matrixes

So, the elements of the product matrix are calculated by taking the dot product of each row of the first matrix (A) with each column of the second matrix (B).

Here’s a breakdown of how each element is calculated:

– Element in the first row, first column: (6*1 + 7*4) 

– Element in the first row, second column: (6*9 + 7*0) 

– Element in the first row, third column: (6*2 + 7*3) 

– Element in the second row, first column: (5*1 + 2*4) 

– Element in the second row, second column: (5*9 + 2*0) 

– Element in the second row, third column: (5*2 + 2*3) 

Make sure to perform the multiplication systematically, taking the dot product for each element. 

Matrix multiplication is widely used in various fields, including computer graphics, physics, engineering, and machine learning. It forms the foundation for solving systems of linear equations and is a fundamental operation in the manipulation of data in many scientific and computational applications.

If you want to know more about C programming, you can go through this C Programming Certification Course!

Code for Matrix Multiplication in C

Now that you have understood how matrix multiplication works, let us now understand the code for matrix multiplication in the C programming language.

#include <stdio.h>
void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int result[][10], int rowsFirst, int colsFirst, int rowsSecond, int colsSecond);
int main() {
    int firstMatrix[10][10], secondMatrix[10][10], result[10][10], rowsFirst, colsFirst, rowsSecond, colsSecond;
    // Input for the first matrix
    printf("Enter the number of rows and columns for the first matrix: ");
    scanf("%d %d", &rowsFirst, &colsFirst);
    printf("Enter elements of matrix 1:\n");
    for (int i = 0; i < rowsFirst; ++i) {
        for (int j = 0; j < colsFirst; ++j) {
            printf("Enter element a%d%d: ", i + 1, j + 1);
            scanf("%d", &firstMatrix[i][j]);
        }
    }
    // Input for the second matrix
    printf("Enter the number of rows and columns for the second matrix: ");
    scanf("%d %d", &rowsSecond, &colsSecond);
    if (colsFirst != rowsSecond) {
        printf("Error! Number of columns in the first matrix should be equal to the number of rows in the second matrix.\n");
        return 0;
    }
    printf("Enter elements of matrix 2:\n");
    for (int i = 0; i < rowsSecond; ++i) {
        for (int j = 0; j < colsSecond; ++j) {
            printf("Enter element b%d%d: ", i + 1, j + 1);
            scanf("%d", &secondMatrix[i][j]);
        }
    }    multiplyMatrices(firstMatrix, secondMatrix, result, rowsFirst, colsFirst, rowsSecond, colsSecond);
   // Displaying the multiplication result
    printf("\nResultant matrix:\n");
    for (int i = 0; i < rowsFirst; ++i) {
        for (int j = 0; j < colsSecond; ++j) {
            printf("%d  ", result[i][j]);
            if (j == colsSecond - 1)
                printf("\n");
        }
    }
    return 0;
}
void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int result[][10], int rowsFirst, int colsFirst, int rowsSecond, int colsSecond) {
    for (int i = 0; i < rowsFirst; ++i) {
        for (int j = 0; j < colsSecond; ++j) {
            result[i][j] = 0;
        }
    }
    for (int i = 0; i < rowsFirst; ++i) {
        for (int j = 0; j < colsSecond; ++j) {
            for (int k = 0; k < colsFirst; ++k) {
                result[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
            }
        }
    }
}

Output:

Enter the number of rows and columns for the first matrix: 2 2

Enter elements of matrix 1:

Enter element a11: 5

Enter element a12: 5

Enter element a21: 8

Enter element a22: 4

Enter the number of rows and columns for the second matrix: 2 2

Enter elements of matrix 2:

Enter element b11: 8

Enter element b12: 6

Enter element b21: 3

Enter element b22: 7

Resultant matrix:

55  65  

76  76  

Get ready for high-paying programming jobs with these Top C & Data Structure Interview Questions and Answers!

Wrap-Up

Understanding and implementing matrix multiplication in C not only enhances a programmer’s ability to optimize algorithms but also enables the development of high-performance applications crucial in industries such as finance, engineering, artificial intelligence, and more. As technology advances, the demand for faster and more efficient computations grows, cementing the significance of matrix multiplication in C as a cornerstone for innovation and progress in diverse industrial domains.

Do you still have doubts about C programming? Clear your doubts and queries with our experts in our C Programming Community!

FAQs

Why is matrix multiplication important in programming?

Matrix multiplication is crucial in programming for various applications like graphics rendering, data analysis, and solving linear equations. It forms the backbone of many algorithms used in fields like machine learning and computer simulations.

How do you perform matrix multiplication in C?

In C, matrix multiplication involves iterating through the rows and columns of matrices, multiplying corresponding elements, and accumulating the results. The process requires nested loops to traverse the matrices and perform the necessary arithmetic operations.

Can matrices of any size be multiplied in C?

Matrices can be multiplied in C as long as the number of columns in the first matrix matches the number of rows in the second matrix. For instance, a matrix with dimensions m x n can be multiplied by a matrix with dimensions n x p to yield a resultant matrix of dimensions m x p.

What are the performance considerations when implementing matrix multiplication in C?

Optimizing matrix multiplication in C involves strategies like loop unrolling, caching data to minimize memory access time, and utilizing parallel processing techniques. Efficient memory allocation and minimizing unnecessary calculations can significantly enhance performance.

Are there any built-in functions/libraries in C for matrix multiplication?

C doesn’t have built-in functions specifically for matrix multiplication. However, libraries like BLAS (Basic Linear Algebra Subprograms) or LAPACK (Linear Algebra Package) provide optimized functions for matrix operations, including multiplication, that can be used in C programs.

Course Schedule

Name Date Details
Python Course 11 May 2024(Sat-Sun) Weekend Batch
View Details
Python Course 18 May 2024(Sat-Sun) Weekend Batch
View Details
Python Course 25 May 2024(Sat-Sun) Weekend Batch
View Details

About the Author

Senior Consultant Analytics & Data Science

Presenting Sahil Mattoo, a Senior Consultant Analytics & Data Science at Eli Lilly and Company is an accomplished professional with 14 years of experience across data science, analytics, and technical leadership domains, demonstrates a remarkable ability to drive business insights. Sahil holds a Post Graduate Program in Business Analytics and Business Intelligence from Great Lakes Institute of Management.

Full-Stack-ad.jpg