Please write these problems in C++ format 33. a) Write a function named scalar_p
ID: 3626519 • Letter: P
Question
Please write these problems in C++ format
33.a) Write a function named scalar_product that passes in 2 vectors of doubles and
returns the scalar product of these 2 vectors. The scalar product for 2 vectors of size
n is:
a0b0 + a1b1 + … + an-1bn-1
The function should return 0 if the vectors are not the same size.
For example, if the function is passed a vector with the values, 1.5, 2.0, 5.5, and a second
vector with the values 4.0, 2.5, 1.0, then the function should return the scalar product 16.5
(1.5*4.0 + 2.0*2.5 + 5.5*1.0 = 16.5).
b) Write a main function that tests this function at least once. For each vector, you may
initialize them with any values you choose, but you must give them at least 3 values each.
Explanation / Answer
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
double scalar_product(vector<double>& v1,vector<double>& v2)
{
double ans=0;
if(v1.size()!=v2.size()) return ans;
for(int i=0; i<v1.size(); i++)
ans = ans + v1[i]*v2[i];
return ans;
}
int main()
{
double a[]={1.5,2.0,5.5};
double b[]={4.0,2.5,1.0};
vector<double> v1(a,a+3);
vector<double> v2(b,b+3);
cout << scalar_product(v1,v2)<<endl;
return 0;
}