# Matrix Multiplication in C

## Matrix Multiplication :

On this page  we will write a basic of C Matrix Multiplication for understanding basic structure of multidimensional array in C programming. In programming , we can multiply two  matrices  easily by using proper syntax and algorithm.

## C Matrix Multiplication Algorithm and Program :

Matrix multiplication is an important program to understand the basics of c programming .For matrix multiplication number of columns in first matrix must be equal to the number of rows in second matrix.Also the number of rows in third matrix which contains the result of multiplication of two matrices is equal to number of row in first matrix and number of columns is equal to number of columns in second matrix.

Algorithm:
• Step 1: Start
• Step 2: Declare matrix mat1[row1][col1]; and matrix mat2[row2][col2]; and matrix mul[row1][col2]; row= no. of rows, col= no. of columns
• Step 3: Read  mat1[row1][col1] and mat2[row2][col2]
• Step 4: Declare variable i=0, j=0
• Step 5: Set a loop from i=0 to i=row1.
• Step 6: Set an inner loop for the above loop from j=0 to j=col2
• Initialise the value of the element (i, j) of the new matrix (mul[row1][col2]) to 0.
• Set an inner loop inside the above loop from k=0 to k=row1.
• Using the add and assign operator (+=) store the value of mat1[i][k] * mat2[k][j] in the third matrix, mul[i][j].
• Print the third matrix.
• Step 7: Stop

## Example: Matrix Multiplication

Run

```#include<stdio.h>
int main ()
{
int mat1[2][3] = { {0, 1, 2}, {3, 4, 5} };
int mat2[3][2] = { {1, 2}, {3, 4}, {5, 6} };
int mul[2][2], i, j, k;

printf ("matrix 1 is :\n");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf ("%d   ", mat1[i][j]);
if (j == 3 - 1)
{
printf ("\n\n");
}
}
}

printf ("matrix 2 is :\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 2; j++)
{
printf ("%d   ", mat2[i][j]);
if (j == 2 - 1)
{
printf ("\n\n");
}
}
}

for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
mul[i][j] = 0;
for (k = 0; k < 3; k++)
{
mul[i][j] += mat1[i][k] * mat2[k][j];
}
}
}

printf ("The product of the two matrices is: \n");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
printf ("%d\t", mul[i][j]);
}
printf ("\n");
}
return 0;
}

```

### Output :

```matrix 1 is :
0   1   2

3   4   5

matrix 2 is :
1   2

3   4

5   6

The product of the two matrices is:
13	16
40	52

```

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others