CSc 17 Test 2 Friday 27 March 1998 Page 1 >>>>>>>>>>>>>>>>>>>>>ANSWERS<<<<<<<<<<<<<<<<<<<<<<<<<< 1. (10 pts) In writing the function below, I forgot to provide the documention. Provide it by stating the pre- and post-conditions. void x (int y[], int m, int n) //Pre-Condition: 0<=m<=n //Post-Condtions: The numbers originally appearing in y[m]...y[n] // are now in reverse order { int t; do { t=y[m]; y[m]=y[n]; y[n]=t; m++; n--; } while (n>m); } 2. (15 pts)Rewrite the following code using only a switch statement. if ( x==1) y=2; else if (x==2) y=7; else if (x==5) y=8; else if ( (x==7) || (x==9)) y=10; else y=13; switch (x) { case 1: y=2; break; case 2: y=7; break; case 5: y=8; break; case 7: case 9: y=10; break; default: y=13; } 3. (25 pts) In many applications the values of a variable cannot be outside some range, e.g., 0.0<=GPA<=4.0, 0<=PERCENT<=100, 0<=AGE<=150. Consider an ADT, for example, with the following properties. Each instance of the ADT stores an integer between 20 and 50 inclusive. One can perform addition, subtraction, multiplication, and division with two instances of the ADT and produce an instance of the ADT, provided the result lies between 20 and 50 inclusive (otherwise an error occurs, and the ADT can no longer be used). One can retrieve the value stored, but one cannot directly change it. One can create an instance of the ADT with a given integer value, provided it is in the range 20 to 50. Write the declaration of a class which implements this ADT. Do not write the definitions of any member functions. class Range { public: Range(); Range(int n); int value(); friend Range operator +(Range a, Range b); friend Range operator -(Range a, Range b); friend Range operator *(Range a, Range b); friend Range operator /(Range a, Range b); private: int val; }; 4. (25 pts) Write the function "equal" such that for the declarations int x[20], y[20], first, last; the call equal(x,y,first,last) returns true if x[i] and y[i] have the same entries for first <= i <= last and returns false otherwise. The function can assume that 0 <= first <= last <= 19. bool equal (int x[], int y[], int first, int last) {bool temp=true; while (temp && first <= last) {temp= x[first]==y[first]; first++; } return temp; } 5. (25 pts) Suppose the file "file.dat" consists entirely of integers. Given the declaration ifstream in; write a function "count" such that the code in.open("file.dat"); cout << "There are "<< count(in) <<" entries\n"; displays on the screen the number of integers in "file.dat". int count(istream & in) { int junk,temp=0; if (!in.eof()) in>>junk; while (!in.eof()) {temp++; in>>junk; } return temp; }