Matrix Multiplication in C
Q. Write a C program for matrix multiplication ?
#include
#include
void main()
{
int m, n, p, q, i, j, k, sum = 0;
int first[5][5], second[5][5], multiply[10][10];
clrscr();
printf("Enter the no of rows and columns for first matrix: ");
scanf("%d %d", &m, &n);
printf("Enter the elements for first matrix\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &first[i][j]);
}
}
printf("Enter the no of rows and columns for second matrix\n");
scanf("%d %d", &p, &q);
printf("Enter the elements for second matrix\n");
for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
scanf("%d", &second[i][j]);
}
}
if (n != p)
{
printf("Matrices can't be multiplied with each other.\n");
}
else
{
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
{
for (k = 0; k < n; k++)
{
sum = sum + first[i][k]*second[k][j];
}
multiply[i][j] = sum;
sum = 0;
}
}
printf("Product of the Matrices:\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
{
printf("%d\t", multiply[i][j]);
}
printf("\n");
}
}
getch();
}
Q. Write an algorithm to matrix multiplication ?
1. Start
2. Input dimensions and elements of the first matrix:
- Read integers `m` and `n` specifying rows and columns for the first matrix.
- Create or declare a matrix `first[m][n]`.
- Loop through each element position `(i, j)` for `i=0 to m-1` and `j=0 to n-1` and read the element for `first[i][j]`.
3. Input dimensions and elements of the second matrix:
- Read integers `p` and `q` specifying rows and columns for second matrix.
- Create or declare a matrix `second[p][q]`.
- Loop through each element position `(i, j)` for `i=0 to p-1` and `j=0 to q-1` and read the element for `second[i][j]`.
4. Check multiplication compatibility:
- If `n` (columns in first matrix) is not equal to `p` (rows in second matrix), then:
- Print "Matrices can't be multiplied with each other."
- Stop the program.
5. Initialize product matrix:
- Create matrix `multiply[m][q]` to store result.
6. Compute the product matrix:
- For each `i` from 0 to `m-1` (each row in first matrix)
- For each `j` from 0 to `q-1` (each column in second matrix)
- Initialize `sum = 0`
- For each `k` from 0 to `n-1` (or `p-1`, same)
- Multiply `first[i][k]` * `second[k][j]` and add to `sum`
- Assign `multiply[i][j] = sum`
7. Print the product matrix:
- For each row `i` from 0 to `m-1`
- For each column `j` from 0 to `q-1`
- Print `multiply[i][j]` followed by a tab
- Print newline after each row
8. End
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com