Open In App

Matrix Multiplication in C

Last Updated : 01 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A matrix is a collection of numbers organized in rows and columns, represented by a two-dimensional array in C. Matrices can either be square or rectangular. In this article, we will learn the multiplication of two matrices in the C programming language.

Example

Input:
mat1[][] = {{1, 2},
            {3, 4}}
mat2[][] = {{5, 6},
            {7, 8}}
Multiplication of two matrices:
{{1*5 + 2*7    1*6 + 2*8},
 {3*5 + 4*7    3*6 + 4*8}}
Output:
{{19, 22},
 {43, 50}}

Multiplication of two matrices is done by multiplying corresponding elements from the rows of the first matrix with the corresponding elements from the columns of the second matrix and then adding these products.

Note: The number of columns in the first matrix must be equal to the number of rows in the second matrix.

C Program to Multiply Two Matrices

We use 2D Arrays and pointers in C to multiply matrices. Please refer to the following post as a prerequisite for the code. How to pass a 2D array as a parameter in C? 

C




// C program to multiply two matrices
#include <stdio.h>
#include <stdlib.h>
 
// matrix dimensions so that we dont have to pass them as
// parametersmat1[R1][C1] and mat2[R2][C2]
#define R1 2 // number of rows in Matrix-1
#define C1 2 // number of columns in Matrix-1
#define R2 2 // number of rows in Matrix-2
#define C2 3 // number of columns in Matrix-2
 
void multiplyMatrix(int m1[][C1], int m2[][C2])
{
    int result[R1][C2];
 
    printf("Resultant Matrix is:\n");
 
    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            result[i][j] = 0;
 
            for (int k = 0; k < R2; k++) {
                result[i][j] += m1[i][k] * m2[k][j];
            }
 
            printf("%d\t", result[i][j]);
        }
 
        printf("\n");
    }
}
 
// Driver code
int main()
{
    // R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these
    // values in MACROs)
    int m1[R1][C1] = { { 1, 1 }, { 2, 2 } };
 
    int m2[R2][C2] = { { 1, 1, 1 }, { 2, 2, 2 } };
 
    // if coloumn of m1 not equal to rows of m2
    if (C1 != R2) {
        printf("The number of columns in Matrix-1 must be "
               "equal to the number of rows in "
               "Matrix-2\n");
        printf("Please update MACROs value according to "
               "your array dimension in "
               "#define section\n");
 
        exit(EXIT_FAILURE);
    }
 
    // Function call
    multiplyMatrix(m1, m2);
 
    return 0;
}


Output

Resultant Matrix is:
3    3    3    
6    6    6    

Complexity Analysis

Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication
Auxiliary Space: O(m1 * n2)

For more information, refer to the article – Program to multiply two matrices



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads