#include #include #include #include // problem #1 // translate the following code /* // sort a vector v // tip! only focus on the OUTER loop for recursion purposes int temp; for (int b = v.length()-1; b > 0; b--) for (int a = 0; a < b; a++) if (v[a] > v[b]) { temp = v[b]; v[b] = v[a]; v[a] = temp; } */ // precondition: b = v.length()-1 void sort(apvector &v, int b) { int temp; if (b == 0) return; else { for (int a = 0; a < b; a++) if (v[a] > v[b]) { temp=v[b]; v[b]=v[a]; v[a]=temp; } sort(v, b-1); } } // problem #2 // translate the following code /* // calculate the integer exponent int pow(int base, int power) { int result = 1; // anything raised to the 0 power is 1 for (power = power; power > 0; power--) { result = result * base; } } */ int pow(int base, int power) { if (power == 0) return 1; else return base * pow(base, power-1); } // problem #3 // translate the following (incorrect) code // calculate the root mean squared /* double rootmeansquare(apvector &a) { double rms = 0.0; for (count = 0; count < a.length(); count++) { rms += a[count] * a[count]; } return sqrt(rms); }*/ // precondition: count = 0, result = 0.0 void rootmeansquare(apvector &a, double &result, int count) { if (count == a.length()) return; else { result += a[count] * a[count]; count++; rootmeansquare(a, result, count); } }