Answer to Question #328236 in C++ for Wedyan

Question #328236

Write a c++ program that computes the product of two matrix ?

  HINT; -Row of the frist matrix should be equal to column of the second matrix.

         - It requires three nested loop.

         - elements of both matrix should be accepted from keyboard.


1
Expert's answer
2022-04-13T09:18:46-0400
#include<iostream>
#include<vector>

using namespace std;


int main()
{
	int rows1, columns1;
	int rows2, columns2;
	cout << "Please, enter a number of rows for the first matrix: ";
	cin >> rows1;
	cout << "Please, enter a number of columns for the first matrix: ";
	cin >> columns1;
	cout << "Please, enter a number of rows for the second matrix: ";
	cin >> rows2;
	cout << "Please, enter a number of columns for the second matrix: ";
	cin >> columns2;
	if ((rows1 != columns2) || (rows2 != columns1))
	{
		cout << "Error! Row of the frist matrix should be equal to column of the second matrix!";
	}
	else
	{
		vector< vector<int> >m1(rows1, vector<int>(columns1));
		vector< vector<int> >m2(rows2, vector<int>(columns2));
		vector< vector<int> >mres(rows1, vector<int>(columns2));
		cout << "Please, enter values for the first matrix: ";
		for (int i = 0; i < rows1; i++)
		{
			for (int j = 0; j < columns1; j++)
			{
				cin >> m1[i][j];
			}
		}
		cout << "Please, enter values for the second matrix: ";
		for (int i = 0; i < rows2; i++)
		{
			for (int j = 0; j < columns2; j++)
			{
				cin >> m2[i][j];
			}
		}
		
		for (int i = 0; i < rows1; i++)
		{
			for (int j = 0; j < columns2; j++)
			{
				mres[i][j]=0;
				for (int k = 0; k < rows2; k++)
				{
					mres[i][j] += m1[i][k] * m2[k][j];
				}
			}
		}
		cout << "\nResulting matrix:\n";
		for (int i = 0; i < rows1; i++)
		{
			for (int j = 0; j < columns2; j++)
			{
				cout << mres[i][j] << " ";
			}
			cout << endl;
		}
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS