Matrix Multiplication in C++
Q. Write a C++ program for matrix multiplication ?
#include <iostream>
using namespace std;
int main()
{
int m, n, p, q, i, j, k, sum = 0;
int first[5][5], second[5][5], multiply[10][10];
cout << "Enter the no of rows and columns for first matrix: ";
cin >> m >> n;
cout << "Enter the elements for first matrix: ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cin >> first[i][j];
}
}
cout << "Enter the no of rows and columns for second matrix: ";
cin >> p >> q;
cout << "Enter the elements for second matrix: ";
for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
cin >> second[i][j];
}
}
if (n != p)
{
cout << "Matrices can't be multiplied with each other.";
}
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;
}
}
cout << "Product of the Matrices:" << endl;
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
{
cout << multiply[i][j] << " ";
}
cout << endl;
}
}
return 0;
}
Q. Write an algorithm to matrix multiplication in c++?
1. Start 2. Input `m` and `n` (number of rows and columns for the first matrix) 3. Input elements of the first matrix of size `m x n`: - For `i` from `0` to `m-1`: - For `j` from `0` to `n-1`: - Read element `first[i][j]` 4. Input `p` and `q` (number of rows and columns for the second matrix) 5. Input elements of the second matrix of size `p x q`: - For `i` from `0` to `p-1`: - For `j` from `0` to `q-1`: - Read element `second[i][j]` 6. Check if matrix multiplication is possible: - If `n` (columns of first matrix) is not equal to `p` (rows of second matrix), print: `"Matrices can't be multiplied with each other."` and stop. 7. Initialize a product matrix `multiply` of size `m x q` with all zeros. 8. Calculate the product matrix: - For `i` from `0` to `m-1`: - For `j` from `0` to `q-1`: - Initialize `sum = 0` - For `k` from `0` to `n-1`: - `sum = sum + (first[i][k] * second[k][j])` - Assign `multiply[i][j] = sum` 9. Print the resulting product matrix `multiply`: - For `i` from `0` to `m-1`: - For `j` from `0` to `q-1`: - Print `multiply[i][j]` followed by a space - Move to the next line after each row. 10. 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