C++ Dot Product using dynamic allocation Write a C++ program that does the follo
ID: 3917616 • Letter: C
Question
C++ Dot Product using dynamic allocation
Write a C++ program that does the following
1. Has the user to input an integer n
2. Dynamically allocates two n-dimensional vectors of doubles
3. Has the user input the components for the two vectors
4. Computes and prints out the dot product
5.Deletes the two vectors
6. All steps above should be in a continuation loop, so the user can repeat the process as many times as they wish
Example input and output from the program
Enter number of components per vector: 2
Enter components for v: 2.1 1.0
Enter components for w: 2.0 1.2
Dot product: 5.4
Compute another dot product (y/n)? y
Enter number of components per vector: 4
Enter components for v: 1 2 3 4
Enter components for w: 2 3 2 -1
Dot product: 10
Compute another dot product (y/n)? n
Here are some few reminders
1. You MUST dynamically allocate the vectors
2. Remember to delete the vectors at the end of each iteration
3. You may assume that all input is valid
Explanation / Answer
ScreenShot
------------------------------------------------------------------
Program
//Header file for I/O
#include<iostream>
using namespace std;
//Main method
int main()
{
//Variable for number vector elements count
int n;
//Two vectors dynamic declaration
double *vec1, *vec2;
//Dot product saving variable
double dotProduct;
//Variable for checking the operation complete or not
char ch='y';
//Loop until 'n' enter
while (ch == 'y') {
//First dotproduct saving variable set to 0
dotProduct = 0;
//Prompt user for vector size
cout << "Enter number of components per vector: ";
cin >> n;
//allocate space
vec1 = new double[n];
vec2 = new double[n];
//Enter values into vectors
cout << "Enter components for v: ";
for (int i = 0; i < n; i++) {
cin >> vec1[i];
}
cout << "Enter components for w: ";
for (int i = 0; i < n; i++) {
cin >> vec2[i];
}
//Calculate dot product
for (int i = 0; i < n; i++) {
dotProduct += (vec1[i] * vec2[i]);
}
//Display dot product
cout << "Dot product: " << dotProduct << endl;
//Delete allocated space
delete[] vec1;
delete[] vec2;
//Loop continuation confirmation prompt
cout << "Compute another dot product (y/n)? ";
cin >> ch;
}
return 0;
}
--------------------------------------------------------------------
Output
Enter number of components per vector: 2
Enter components for v: 2.1 1.0
Enter components for w: 2.0 1.2
Dot product: 5.4
Compute another dot product (y/n)? y
Enter number of components per vector: 4
Enter components for v: 1 2 3 4
Enter components for w: 2 3 2 -1
Dot product: 10
Compute another dot product (y/n)? n
Press any key to continue . . .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.