In C++, Write a function which overloads the multiplication operator * to multip
ID: 3753708 • Letter: I
Question
In C++,
Write a function which overloads the multiplication operator * to multiply a 1 x 4 matrix by a 4 x 1 matrix. Write a program which tests your function similar to the overloading + example. Your function should mutliply corresponding elements of the arrays and return the sum. If you put function definition outside the class, then it will take 2 arguments as below;
int operator*(ARRAY& A, ARRAY& B) {
int sum = 0;
for(int k = 0; k<4; k++)
{ sum = sum + A.a[k] * B.a[k] ;
}
return sum;
}
NOTE: PLEASE READ THE QUESTION CAREFULLY AND TAKE A LOOK AT THE OVERLOADING + EXAMPLE FIRST. THE PROGRAM ASKED IN THE QUESTION MUST BE EXACTLY IN THAT FORMAT, NO OTHER METHODS WILL BE ACCEPTED. PLEASE KEEP THAT IN MIND, SO I DON'T HAVE TO GIVE A DOWNVOTE FOR YOUR SOLUTION.
THANK YOU.
// The Overloading + Example mentioned in the question starts here.
Explanation / Answer
Hi,
As you demand i try to create a specific program which fulfill your requirements. This is not a general program
that takes two matrix n*m and m*o and produce resultant matrix n*o. But as you instruct to dont change the format here is
your program I hope you will fully understand it by comments in program:
#include<iostream>
using namespace std;
class ARRAY
{
public:
int a[1][4]; //first Array for multiplication 1*4 matrix
int b[4][1]; //second Array for multiplication 4*1 matrix
int operator*( const ARRAY& A)
{
int sum=0;
for(int i=0;i<1;i++) //i< number of row in 1st matrix
{
for(int j=0;j<1;j++) //j<number of coloumn in 2nd matrix
{
for(int k=0;k<4;k++) //k< number of coloumn in first matrix
{
sum = sum+(this->a[i][k])*A.b[k][j];
}
}
}
return sum;
};
};
int main()
{
ARRAY arr1, arr2;
for(int i=0; i<4; i++)
for(int j=0;j<1;j++)
{
arr1.a[j][i]=i;
arr2.b[i][j]=4*i;
}
int z;
z = arr1*arr2; //multiplication is stored in z
cout<<"===== "<<endl;
cout<<z<<endl;
return 0;
}