In C language, Matrix can be formed with the help of an array. Matrix is a useful concept of Mathematics. It is a set of m*n elements of an array where m is the number of rows and n is the number of columns. The matrix can be represented with the help of 2-D arrays and various Arithmetic Operations can be performed on the Matrices. Here we discuss Matrix Multiplication in C.
Matrix Multiplication in C
Initialization of Matrix in the C int M[4][5] // here M is a matrix or 2D array having 4 rows and 5 columns.
Arithmetic Operations performed on Matrix in C
- Matrix Addition
- Matrix Subtraction
- Matrix Multiplication
In this article, we will discuss the Matrix Multiplication in C. Let’s start with this. The Multiplication of the matrix is different from the other Addition and Subtraction Arithmetic operations of matrices. In matrix multiplication, the order of the matrices does not matter. Consider if you have 2 matrices Am*n and Bi*j and A and B undergo Matrix multiplication such that C = A*B the new matrix will become Cm*j.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
// matrix A and B, and C for multication result
int A[10][10], B[10][10], C[10][10];
// ask the total number of rows and coloumns
printf("Enter the Number of Rows and Columns for Matrix A\n");
scanf("%d%d", &m, &n);
printf("Enter the Elements of A\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &A[c][d]);
printf("Enter the Number of Rows and Columns for Matrix B\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter the Elements of B\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &B[c][d]);
//multiplication start
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + A[c][k]*B[k][d];
}
C[c][d] = sum;
sum = 0;
}
}
printf("Matrix Multiplication is:\n");
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
printf("%d\t", C[c][d]);
printf("\n");
}
}
return 0;
}
OUTPUT
Enter the Number of Rows and Columns for Matrix A
3
3
Enter the Elements of A
1
1
1
2
2
2
3
3
3
Enter the Number of Rows and Columns for Matrix B
3
3
Enter the Elements of B
1
2
3
4
5
6
7
8
9
Matrix Multiplication is:
12 15 18
24 30 36
36 45 54
Points to Remember
- A*B is not equal to B*A
- A*(B*C) == (A*B)*C
- If C= A*B, then the order of matrix C will be the m*j, where m is the number of Rows of Matrix A and j is the number of Columns of Matrix B.
You might be also interested in:
Leave a Comment on this Post