Midterm Make-up problems

1. Input a positive integer N and compute and print the sum

1 + {1\over 2^2} + {1\over 3^2} + {1\over 4^2} + \dots + {1\over N^2}\end{displaymath}

(It is known that as N tends to infinity, the above sum gets ever closer to ${\pi^2 \over 6}$, so if you take N large enough, and compute the above sum S, then find sqrt(6*S), you get Pi.)

2. (String to Integer conversion) The user inputs a string that represents an integer number (positive or negative). Write a function int StringToInt( string s ) that returns the integer that the string represents.

You have to check if the string indeed represents a number (in particular, no characters other than digits and '-' are allowed in the string, and '-' can only occur in the leading position). Your function must print an informative error message and exit if the input string is invalid.

Your main function should prompt the user for strings, convert them to integers and print the results, until the user enters a string which does not correspond to a number, or an empty string.

Extra credit: write a function double StringToDouble( string s ).

3. Write a program that prompts the user for a word and the name of a text file, then opens the file and counts how many times that word occurs in that file (and prints the count). Then prompt the user for another word and count how many times it occurs in the same file, etc. Continue until the user enters the word ``bye''.

4. Extra credit. Write a program that counts the number of different words in a text file.

A solution that works fast and is memory efficient requires a few things that we didn't discuss, such as dynamic memory allocation (operators new and delete, and data structures that allow efficient search (hashes or binary search trees). For now, you can simplify the problem by assuming that your text file is small (less than 1000 words) and that time is not a factor).

Sergey Bratus