CSc 17 Final Examination Tuesday 18 December 2001 >>>>>>>>>>>>>>>>>>>>>>>>SUGGESTED ANSWERS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 1. (25 pts) The code below will compile but not link, because the function f() is not defined. Add code for a single function f() to the code below so that the code compiles and runs and produces the output between the dashed lines. #include void a(int x) {cout<<(x*x)< void f(T g,V x){ g(x); } 2. (25 pts) Assume that the class Node below is used to build a binary tree. Further assume that as the tree is built the height of each Node is stored in the data member 'height'. Write a function balanced() which returns 'true' if and only if the tree is balanced. If rt is declared as Node *rt, the call to determine whether the binary tree with root rt is balanced would be balanced(rt). class Node {public: double data; int height; Node *child[2]; }; ANSWER ------------- int h(Node *rt) {if(rt==NULL) return -1; return rt->height; } bool balanced(Node *rt) {if(rt==NULL) return true; int lHt,rHt; bool tBal; lHt=h(rt->child[0]); rHt=h(rt->child[1]); tBal=lHt-rHt<2 && rHt-lHt<2; return balanced(rt->child[0]) && balanced(rt->child[1]) && tBal; } 3. (25 pts) Write a function, g, which reads text from a file f, of type istream, and displays a faithful copy of the file on the screen, except that it appends an asterisk (*) after every line whose first character is a digit (0, 1, ..., 9) and whose last character is a period (.). The call to the function would read g(f). ANSWER -------- void getch(istream &f,char &ch) {if(f.good()) f.get(ch); if(!f.good()) ch='\n'; } void g(istream &f) {bool digit; char ch,oldch; getch(f,ch); while(!f.eof()) {digit=ch>='0' && ch<='9'; while(ch!='\n') {cout<>x; while(!in.eof()) {st.push(x); q.enqueue(x); in>>x; } while(!st.empty()) cout< #include int main() { SafeIntArray list(20); for(int j=0;j<14;j++) list.store(j,2*j+3); cout<=max,"array index out of bounds"); data[index]=value; } int SafeIntArray::get(int index) {errCheck(index<0 || index>=max,"array index out of bounds"); return data[index]; } void SafeIntArray::errCheck(bool b,char *mess) {if(b) {cerr<<"ERROR: "<=0 && x[n]>target); if(n<0 || x[n]!=target) return -1; return n; //*/ a more efficient (binary) search is below /* int bot,mid; bot=0; n--; while(n>bot+1) {mid=(n+bot)/2; if(x[mid]