// ENGR 131, Monday 3:30 Recitation (Amanda Rohn) // HW #6, Part B - Dot Products #include #include "useful.h" using std::cin; using std::cout; using std::endl; using aer::GetDouble; double Dot(double a[], int a_size, double b[], int b_size); int main() { const int SIZE = 3; cout << "This program can calculate the dot product of two vectors (a and b) of length 3.\n"; double a[SIZE], b[SIZE]; cout << "Please enter the three elements of vector a at the prompts.\n"; for(int i = 0; i < SIZE; i++) a[i] = GetDouble("Element of a"); cout << "Now enter the elements of vector b.\n"; for(int j = 0; j < SIZE; j++) b[j] = GetDouble("Element of b"); cout << "\nThe dot product of those vectors is " << Dot(a,SIZE,b,SIZE) << endl; return 0; } double Dot(double a[], int a_size, double b[], int b_size) { //if the sizes don't match, we assume that the extra elements in the smaller vector //are equal to zero. This is equivalent to calculating the dot product only for those //elements that exist in both vectors, so use the smaller size. int size = (a_size <= b_size) ? a_size : b_size; double dp = 0; //the dot product is found by summing the products of the matching elements in each vector for(int i = 0; i < size; i++) dp += a[i] * b[i]; return dp; }