Skip to content

Instantly share code, notes, and snippets.

@afishr afishr/matrix.cpp
Last active Oct 31, 2018

Embed
What would you like to do?
//matrix_multiplication
int main()
{
int a, b, c, d;
// Entering the matrices dimensions
do
{
cout << "M1 dimensions: ";
cin >> a >> b;
cout << "M2 dimensions: ";
cin >> c >> d;
if (b != c)
{
cout << endl << "Matrices cannot be multiplicated" << endl;
cout << "Re-enter values or close program" << endl << endl;
}
} while (b != c);
// Creating and filling the matrices
auto** m1 = new int*[a];
auto** m2 = new int*[c];
auto** m3 = new int*[a];
for (int i = 0; i < a; i++)
*(m1+i) = new int[b];
for (int i = 0; i < c; i++)
*(m2+i) = new int[d];
for (int i = 0; i < a; i++)
*(m3+i) = new int[d];
cout << endl << "First matrix " << a << " x " << b << ": " << endl;
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
cin >> *(*(m1+i)+j);
}
cout << endl << "Second matrix " << c << " x " << d << ": " << endl;
for (int i = 0; i < c; i++)
{
for (int j = 0; j < d; j++)
cin >> *(*(m2+i)+j);
}
for (int i = 0; i < a; i++)
{
for (int j = 0; j < d; j++)
*(*(m3+i)+j) = 0;
}
// =============
for (int i = 0; i < a; i++)
{
for (int j = 0; j < d; j++)
{
for (int k = 0; k < b; k++)
{
m3[i][j] += m1[i][k] * m2[k][j];
}
}
}
cout << endl << "Resulting matrix: " << endl;
for (int i = 0; i < a; i++)
{
for (int j = 0; j < d; j++)
cout << m3[i][j] << " ";
cout << endl;
}
// Freeing the memory
for (int i = 0; i < a; i++)
delete [] *(m1+i);
delete [] m1;
for (int i = 0; i < c; i++)
delete [] *(m2+i);
delete [] m2;
for (int i = 0; i < a; i++)
delete [] *(m3+i);
delete [] m3;
_getch();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.