Need a project done?

C++ Programming Developer

Search This Blog

Multiply 2 Matrices of any order in C++


//Multiply 2 Matrices of any order in C++
#include <iostream>
using namespace std;

int main()
{
cout << "Size of Matrix A:";
int rows1, columns1;
cin>>rows1>>columns1;
//Initializing a 2-d dynamic array.
int ** m1 = new int *[rows1];

for (int i = 0; i<rows1; i++)
m1[i] = new int [columns1];

//Inputing Matrix.
cout << "Enter Matrix A\n";
for (int r = 0; r<rows1; r++)
for (int c = 0; c<columns1; c++)
cin>>m1[r][c];
//--------------------------------------
cout << "Size of Matrix B:";
int rows2, columns2;
cin>>rows2>>columns2;

int ** m2 = new int *[rows2];

for (i = 0; i<rows2; i++)
m2[i] = new int [columns2];

//Inputing Matrix.
cout << "Enter Matrix B\n";
for ( r = 0; r<rows2; r++)
for (int c = 0; c<columns2; c++)
cin>>m2[r][c];
//--------------------------------------

//Printing Matrix A.
cout << "\nA:\n";
for ( r = 0; r<rows1; r++)
{
for (int c = 0; c<columns1; c++)
cout << m1[r][c] << ' ';

cout << endl;
}

//Printing Matrix B.
cout << "\nB:\n";
for ( r = 0; r<rows2; r++)
{
for (int c = 0; c<columns2; c++)
cout << m2[r][c] << ' ';

cout << endl;
}


int result = 0;
//A*B

cout << endl <<endl << "A*B =";
for (int constR = 0; constR < rows1; constR++)
{
cout << endl;
for (int constC = 0; constC < columns2; constC++)//for Next element
{
result = 0;
r = 0;
for (int c = 0; r<rows2; r++,c++)//calculating each element
{
result +=  m1[constR][c] * m2[r][constC];
}
cout << result<< ' ';
}
}

return 0;
}

No comments:

Post a Comment

"Don't let anyone ever make you feel like you don't deserve what you want."