Midterm Key CS31 (Shinnerl) Winter 06 Part I. d b c b d c e c d d b f f a c e d b c Part II. #20 Constructs a positive integer from an array of digits stored as characters. (Converts a C-style string representation of an integer value to its "int" representation.) #21 a. 2 b. 3 c. 3 d. 3.75 e. 2.0 #22 Modular design: the program is organized as a collection of small, loosely coupled functions interacting through prescribed interfaces. I.e., preconditions and postconditions on function parameters are carefully enforced. Comments, consistent naming conventions and indentation, and structured control flow are also very important. Part III. #23 a. int scoreCount(int a[], int n, int s) { int count = 0; for (int i = 0; i < n; i++) { if (s == a[i]) count++; } return count; } b. int mode(int a[], int n) { int index = 0; int count = 0; int highest = 0; for (int i = 0; i < n; i++) { count = scoreCount(a, n, a[i]); if (count > highest) { highest = count; index = i; } } return a[index]; } #24 a. /* Find a match phrase starting from the pos in text Compare each character until there is mismatch or there is no more characters in phrase or text Parameters: phrase - phrase to match text - text to match against pos - starting position in text Returns: 0 - no match 1 - match */ int matchString(char phrase[], char text[], int pos) { int i = 0; while (phrase[i] && text[pos]) { if (phrase[i++] != text[pos++]) return 0; } //reached the end of phrase? if (phrase[i]) return 0; return 1; } int substringStart(char phrase[], char text[]) { int i = 0; while (text[i]) { if (matchString(phrase, text, i)) return i; i++; } return -1; } b. int phraseCount(char phrase[], char text[]) { int count = 0; int i = 0; while (text[i]) { if (matchString(phrase, text, i)) count++; i++; } return count; }