![]() |
VOOZH | about |
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.
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.
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?
Resultant Matrix is: 3 3 3 6 6 6
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