Courses

### Courses

Structure and Union

No Examples found for this topic - CodeHelpPro

Data Files

No Examples found for this topic - CodeHelpPro

# Program for Matrix Multiplication

0 June 15, 2021

In this example, We will learn a program for matrix multiplication. Before that, You must have knowledge of the following topics.

## Rules for Matrix Multiplication

Here are the few important notes you must know for matrix multiplication

• We can multiply matrix if only number of columns of first matrix = number of rows of second matrix
``````1    2   3   6      2  8  0
3    4   2   0  *   4  6  2
1  2  0
4 COLUMNS        0  1  4
4 ROWS

4 COLUMNS = 4 ROWS
``````

## Step for Matrix Multiplication

To perform the matrix multiplication

• Step 1: Make sure number of columns of 1st column is equal to rows of second columns.
• Step 2: Multiply elements of each rows of first matrix to the each columns of second marix
• Step 3: Add the products

## CODE: Program for Matrix Multiplication

Now, We will see the code to sort array elements using for loop.

``````#include<stdio.h>

int main(){

int n, m, c, d, p, q, k, first[10][10], second[10][10], pro[10][10],sum = 0;

printf("\nEnter the number of rows and columns of the 1st matrix: \n\n");
scanf("%d%d", &m, &n);

printf("\nEnter the %d elements of the 1st matrix: \n\n", m*n);
for(c = 0; c < m; c++)
for(d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("\nEnter the number of rows and columns of the 1st matrix: \n\n");
scanf("%d%d", &p, &q);

if(n != p){

printf("Matrices with the given order cannot be multiplied with each other.\n\n");

} else {

printf("\nEnter the %d elements of the 2nd matrix: \n\n",m*n);

for(c = 0; c < p; c++)
for(d = 0; d < q; d++)
scanf("%d", &second[c][d]);

// printing the 1st matrix
printf("\n\nThe 1st matrix is: \n\n");
for(c = 0; c < m; c++)
{
for(d = 0; d < n; d++)
{
printf("%d\t", first[c][d]);
}
printf("\n");
}

// printing the 2nd matrix
printf("\n\nThe 2nd matrix is: \n\n");
for(c = 0; c < p; c++)
{
for(d = 0; d < q; d++)
{
printf("%d\t", second[c][d]);
}
printf("\n");
}

for(c = 0; c < m; c++)
{
for(d = 0; d < q; d++)
{
for(k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}
pro[c][d] = sum;
sum = 0;
}
}

// printing the elements of the product matrix
printf("\n\nThe multiplication of the two entered matrices is: \n\n");
for(c = 0; c < m; c++)
{
for(d = 0; d < q; d++)
{
printf("%d\t", pro[c][d]);
}
printf("\n");
}
}

return 0;
}``````

The output of above program is

``````
Enter the number of rows and columns of the 1st matrix:

2
2

Enter the 4 elements of the 1st matrix:

1
2
3
4

Enter the number of rows and columns of the 2nd matrix:

2
2

Enter the 4 elements of the 2nd matrix:

7
5
3
2

The 1st matrix is:

1       2
3       4

The 2nd matrix is:

7       5
3       2

The multiplication of the two entered matrices is:

13      9
33      23``````
Subscribe
Notify of
Inline Feedbacks