Winter 04 CS 31 (SHINNERL) Midterm Solutions VERSION II (PINK) ------------------- ------------------------ Part I: MULTIPLE CHOICE. ------------------------ Question: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Answer: b b a c c e a b f d d e d a b e b d f d c (e) The correct answer to Q3 is of course (a), but if the typo in the question is corrected (change cout << i to cout << a[i]), then the correct answer is (e). Full credit was given to both (a) and (e) for this question. ----------------------- Part II: SHORT ANSWER. ----------------------- Question 22 ----------- (a) (d + s - 2) % 10 + 1 (b) (d + s - 2) / 10 + 1 (c) Yes, leap years are still needed, because the time in one year (the time it takes the earth to go around the sun once) is still not an integer multiple of the time in one day (the time it takes the earth to spin around once). We have not changed the length of a day. ------------------ Part III: CODING. ------------------ Question 23 ----------- void histogram( char str[], int freqs[] ){ // Precondition: Given length of freqs >= 26. // Ignores nonalphabetical characters. // Treats lower and upper case letters the same way (case insensitive). for (int i = 0; i < 26; ++i) // Clear the histogram. freqs[i] = 0; for (int i = 0; str[i]; ++i) if ( 'a' <= str[i] && str[i] <= 'z' ) ++freqs[ str[i] - 'a' ]; // lower case else if ( 'A' <= str[i] && str[i] <= 'Z' ) ++freqs[ str[i] - 'A' ]; // upper case } // Question 24 (a) // ----------- void printHistVert( int freqs[] ){ // Precondition: Given length of freqs >= 26. // Ignores nonalphabetical characters. // Treats lower and upper case letters the same way (case insensitive). for (int i = 0; i < 26; ++i){ for (int j = 0; j < freqs[i]; ++j) std::cout << char('a' + i); std::cout << std::endl; } } // Question 24 (b) // ----------- int maxValue( int a[], int n ){ // Find and return the maximum value in an int array of length n. int maxSoFar = a[0]; for (int i = 1; i < n; ++i) if (maxSoFar < a[i]) maxSoFar = a[i]; return maxSoFar; } void printHistHoriz( int freqs[] ){ // Precondition: Given length of freqs >= 26. // Ignores nonalphabetical characters. // Treats lower and upper case letters the same way (case insensitive). int maxFreq = maxValue( freqs, 26 ); for (int i = maxFreq; i > 0; --i){ for (int j = 0; j < 26; ++j) if ( freqs[j] >= i ) std::cout << char('a'+ freqs[j]) << ' '; else std::cout << ' ' << ' '; std::cout << std::endl; } }