Comp 1572, Winter 2002 Pencil-and-Paper Assignment 4 Assigned Monday, February 4, 2002 Due Monday, February 11, 2002 (At the beginning of class) ============================================================================ This is pencil-and-paper homework. Write your answers as neatly as possible. If your handwriting is hard to read, please type your answers. Please begin this assignment early, so that you have time to ask questions if you have difficulty. ============================================================================ 1. Change the following program segment to use pass-by-pointer instead of pass-by-reference. The program should behave the same after you make your changes. void increment(int &, int); void main() { int num(5); int inc_amount(2); increment(num, inc_amount); } // increments value by increment_amt increment(int &value; int increment_amt) { value += increment_amt; } 2. The following program doesn't work: void linear_search(int *, int, int); void main() { int arr[6] = {1, 26, 109, 42, 47, 1010}; int *iptr; iptr = arr; linear_search(iptr, 6, 47); // search array for 47, memory location // of this key should be stored in iptr cout << *iptr; // I want it to display "47", but instead it displays "1" } // ip points to beginning of array of length len. Search the array for key, // and "return" memory location of that value in ip void linear_search(int *ip, int len, int key) { for(i=0; i< len; i++) if (ip[i] == key) { ip = &ip[i]; return; } ip = 0; // key not found! } The hope was that linear_search would give us a pointer to the location in the array where the search key was located by updating iptr. It doesn't work, but can be fixed by making the first parameter to linear_search be an int **. Change the code in this way so it works. 3. problem in distinguishing between types of pointer consts Given the following definitions char p[] = "Yikes!"; char c='F'; const char *pc; char *const cp; const char * const ccp; char const *ppc; // warning, this one is a trick question! Which of the following statements generate errors and which do not? pc[5] = 'A'; pc = p; *(cp) = 'Z'; cp = &c; ccp[5] = p[5]; ccp = &p[3]; *(ppc+1) = 0; ppc = pc; 4. Take the following function void traverse_with_index(char v[]) { for (int i=0; v[i] != 0; i++) do_something(v[i]); } and change it so that the array is traversed with a pointer and pointer- offset notation instead of with an integer and subscripting. Replace for (int i...) with for (char *p...). The call to do_something will have to be changed as well. 5. Do problem 5.21 in Deitel and Deitel 6. Do problem 5.22 in Deitel and Deitel 7. Do problem 5.23 in Deitel and Deitel 8. Implement the quicksort algorithm as described in Deitel and Deitel problem 5.24. Implement both the recursive function quicksort and the function partition to sort a vector of doubles.