// CSE 143 Sp 01 Homework 2.5 // Programming question sample solution // HP 4/01 #include using namespace std; // = a1*b1 + a2*b2 + ... + an*bn (origin 1 vectors) double dotProduct(double a[], double b[], int n) { double result = 0.0; for (int k = 0; k < n; k++) { result = result + a[k]*b[k]; } return result; } // = new vector containing [a1+b1, a2+b2, + ... + an+bn] double *vectorSum(double a[], double b[], int n) { double *result = new double[n]; for (int k = 0; k < n; k++) { result[k] = a[k] + b[k]; } return result; } // print vector v with n elements // assumption: n > 0 void printVector(double v[], int n) { cout << "[" << v[0]; for (int k = 1; k < n; k++) { cout << ", " << v[k]; } cout << "]"; } // read n and two vectors of length n // print the vectors, their dot product, and their sum, int main() { int n; // vector lengths double *v, *w; // input vectors double *sum; // vector sum v+w double dotprod; // dot product int k; // allocate and read vectors cout << "Please enter vector length: "; cin >> n; v = new double[n]; w = new double[n]; cout << "enter " << n << " numbers for first vector: "; for (k = 0; k < n; k++) cin >> v[k]; cout << "enter " << n << " numbers for second vector: "; for (k = 0; k < n; k++) cin >> w[k]; // calculate results and print everything dotprod = dotProduct(v,w,n); sum = vectorSum(v,w,n); cout << "First vector: "; printVector(v,n); cout << "\nSecond vector : "; printVector(w,n); cout << "\nDot product = " << dotprod; cout << "\nVector sum = "; printVector(sum,n); cout << endl; // delete dynamic storage delete [] v; delete [] w; delete [] sum; return 0; }