You are on page 1of 4

CS107 J Zelenski

Handout #2 May 1, 2013

Midterm practice
Midterm Exam: Friday May 10th 11am-12:15pm Cubberley Aud (last name begins with A-M) Annenberg Aud (last name begins with N-Z)

Please note the exam will be given in two separate locations. Your assigned location is dicated by the first letter of your last name. Be sure to note the location you are to attend! SCPD students: Local SCPD students attend the regular on-campus exam. Those outside the Bay Area should arrange for your SCPD site coordinator to administer the exam onsite to you on Friday. Remote students must send e-mail to our Head TA Michael (mchang91@stanford.edu) by Monday May 6 to initiate arrangements for an on-site exam. Local students should bring a completed routing form to attach to your exam, remote students should return the completed exam with a routing form. . (http://scpd.stanford.edu/generalInformation/pdf/SCPD_HomeworkRouteForm.pdf) One page of notes You may bring a single sheet of paper (double-sided, size 8.5" x 11") prepared with your written/printed notes. The printed exam will include a list of relevant stdlib function prototypes. No additional written materials and no electronic devices/resources are be used during the exam. Material Our exams focus on evaluating your mastery of the material that figured prominently in the labs and assignments. For the midterm, this means questions that delve into strings, pointers, arrays, function pointers, low-level memory manipulation, and data representation (e.g. bits, ints, floats). The midterm will not test IA32 assembly. The rest of this handout is the midterm I gave most recently in CS107 so you can consider the questions fairly representative in terms of format, difficulty, and content. To conserve paper, I cut back on answer space. The real exam will have more room for your answers and scratch work. We'll distribute solutions separately. There are also many excellent problems in the K&R and B&O texts if you want further practice. Further advice See my manifesto of advice and encouragement on how to prepare for and crush a CS107 examy. Youll find it on our web site at https://courseware.stanford.edu/pg/pages/view/347660/exam-advice

2 Problem 1: C-strings Write the Trim function that takes a string word and an integer n and destructively modifies word to remove its first and last n characters if those sequences match. The modification alters the characters in word, but there is no change in the memory allocated. If its first and last n characters do not match, word is unchanged. Here are some examples: Trim("decided", 1) changes word to "ecide" Trim("radar", 2) doesn't change word Trim("bonbon", 3) changes word to "" Trim("comic",2) doesn't change word It is important to note that strcpy/strncpy cannot be used when the source and destination overlap.
void Trim(char *word, int n) { assert(n > 0 && n <= strlen(word)/2);

Problem 2: Implementing and using C generics a) The function Reduce processes the elements from an array into a single result by repeatedly applying the client's two-argument function to an element and the existing result until all elements have been folded in. As an example, a client could use Reduce to sum an array of integers by creating an integer result initialized to zero and a callback function to add each element to the result. You are to implement Reduce. The function arguments are the base address of the array, the number of array elements, the size of each element in bytes, the callback function, and the result pointer. The array elements and result can be of any type desired by the client and are handled as void*s. The callback function is called once for each array element; the elements are processed in order of ascending array index. The two arguments passed to the client's callback are the result pointer and the address of the array element, in that order.
/* The client callback arguments are the result pointer and the * address of an array element. The function "combines" that * element into the result. */ typedef void (*combineFn)(void *result, const void *elemAddr); void Reduce(void *base, size_t nElems, size_t elemSz, combineFn fn, void *result)

b) Use Reduce to implement the function Longest that finds the longest string in an array and returns it. If the array has no elements, the function returns NULL. If there is more than one string of maximal length, any can be returned. Your implementation must operate by using the Reduce function from part (a) and can assume it works correctly. You will need to write a callback function. Do not copy/duplicate the string, just return the string found in the array.
char *Longest(char *arr[], int nElems)

3 Problem 3: Bits, bytes, and numbers This problem concerns implementing a function to average two integers. We define the correct average as the integer midway between the two, rounding any fraction toward zero. Average(3, 9) should be 6, Average(1, 8) should be 4, and Average(-1, -8) should be -4. Assume 32-bit two's complement integers and 32-bit IEEE floats. a) True or false: for any two integer inputs, their correct average is representable as a int. If false, provide a counterexample. b) Consider the two possible implementations of the Average function below:
int Average1(int a, int b) { return (a + b)/2; } int Average2(int a, int b) { return ((unsigned)a + b) >> 1; }

The functions above compute the correct average for some inputs, but not all, and the failure cases are not necessarily the same for both. The table below diagrams the possibilities. The upper-left cell has the parameters filled for an example call that obtains a correct result from both Average1 and Average2. For the remaining three cells, you are to fill in the blanks with parameters for a call that obtains the results indicated from Average1/Average2 or write "None" if no such input exists. The parameters you fill in should be integer constants/expressions written in legal C code.
Average1 Average2

correct result

Average1

incorrect result

correct result
Average2

) (

incorrect result (

) (

c) Consider this third approach for computing the average:


int Average3(int a, int b) { return ((float)a + b)/2; }

True or false. This function returns the correct average for all integer inputs. If false, provide a counterexample.

4 Library functions
Reminder of the prototypes for potentially useful functions. You won't use every function listed. You may also use standard C library functions not on this list. size_t strlen(const char *str); char *strcpy(char *dst, const char *src); char *strncpy(char *dst, const char *src, size_t n); char *strcat(char *dst, const char *src); char *strncat(char *dst, const char *src, size_t n); char *strchr(const char *s, int ch); char *strrchr(const char *s, int ch); char *strstr(const char *haystack, const char *needle); int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); void *malloc(size_t sz); void *realloc(void *ptr, size_t sz); void free(void *ptr); void *memcpy(void *dst, const void *src, size_t n); void *memmove(void *dst, const void *src, size_t n);

You might also like