Answer to Question #200846 in C++ for Anonymous Programm

Question #200846

Write a C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays. You can use int or double

2D array and takes it input from user. This program takes two matrices of order r1*c1 and r2*c2

respectively. Then, the program multiplies these two matrices (if possible) and displays it on the screen,

please take input from user.


1
Expert's answer
2021-05-30T13:35:15-0400
#include <iostream>


using namespace std;


//This function allows to fill matrix
void getMatrixValues(double array2D[][20],int rows, int columns){
	for(int i = 0; i < rows; i++){
		for(int j = 0; j < columns; j++){
			cout << "Enter ["<< i<<"]["<< j << "]: ";
			cin >> array2D[i][j];
		}
	}
}


//The start point of the program
int main()
{
	//matrices arrays
	double array2D1[20][20];
	double array2D2[20][20];
	double result[20][20];


	int numberRowsarray2D1;
	int numberColumnsarray2D1;
	int numberRowsarray2D2;
	int numberColumnsarray2D2;




	numberRowsarray2D1=-1;
	while(numberRowsarray2D1<1){
		cout<<"Enter the number of rows of matrix 1: ";
		cin>>numberRowsarray2D1;
	}
	numberColumnsarray2D1=-1;
	while(numberColumnsarray2D1<1){
		cout<<"Enter the number of columns of matrix 1: ";
		cin>>numberColumnsarray2D1;
	}
	


	numberRowsarray2D2=numberColumnsarray2D1-1;
	while (numberColumnsarray2D1 != numberRowsarray2D2){
		numberRowsarray2D2=-1;
		while(numberRowsarray2D2<1){
			cout<<"Enter the number of rows of matrix 2: ";
			cin>>numberRowsarray2D2;
		}


		numberColumnsarray2D2=-1;
		while(numberColumnsarray2D2<1){
			cout<<"Enter the number of columns of matrix 2: ";
			cin>>numberColumnsarray2D2;
		}


		if(numberColumnsarray2D1 != numberRowsarray2D2){
			cout << "\nThe column of the matrix 1 is not equal to the row of matrix 2.\n\n";
		}
	}
	cout<<"\nFill the matrix 1:\n";
	getMatrixValues(array2D1,numberRowsarray2D1,numberColumnsarray2D1);
	cout<<"\n\nFill the matrix 2:\n";
	getMatrixValues(array2D2,numberRowsarray2D2,numberColumnsarray2D2);


	for(int i = 0; i < numberRowsarray2D1; i++){
		for(int j = 0; j < numberColumnsarray2D2; j++){
			result[i][j] = 0;
		}
	}


	for(int i = 0; i < numberRowsarray2D1; i++){
		for(int j = 0; j < numberColumnsarray2D2; j++){
			for(int k=0; k<numberColumnsarray2D1; k++)
			{
				result[i][j] += array2D1[i][k] * array2D2[k][j];
			}
		}
	}
	
	cout << "\nThe product result of two matrices:\n";	
	for(int i = 0; i < numberRowsarray2D1; i++){
		for(int j = 0; j < numberColumnsarray2D2; j++){
			cout<<result[i][j]<<"\t";
		}
		cout<<"\n";
	}
	system("pause");
	return 0;
}




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