CSC 161 Grinnell College Fall, 2011
Imperative Problem Solving and Data Structures

Supplemental Problems

Supplemental Problems extend the range of problems considered in the course and help sharpen problem-solving skills. Problems numbered 6 or higher may be turned in for extra credit.

Quick links: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14

This page will evolve as the semester progresses. I hope to have each supplemental problem finalized at least 1 week before it is due.


In turning in any programs for the course, please follow these directions:
  1. The first six lines of any C program should be comments containing your name, your mailbox number, this course number (161), and an identification of assignment being solved. For example:
         * Henry M. Walker                     *
         * Box Science II                      *
         * Program for CSC 161                 *
         * Assignment for Tuesday, February 10 *
    Also, a comment is needed for every definition of a C function, stating both pre- and post-conditions for that program unit.

  2. Obtain a listing of your program and a record of relevant test runs using the script command:

  3. Either write on your printout or include a separate statement that argues why your program is correct, based upon the evidence from your test runs.

Some Grading Notes:

Computing the Greatest Common Divisor (Euclidean Algorithm)

  1. [The following is an edited and abridged version of Section 4.1 from Problems for Computer Solutions Using FORTRAN by Henry M. Walker, Winthrop Publishers, 1980 and is used with permission of the copyright holder.]

    Let N and M be two positive integers. The greatest common divisor of N and M, denoted gcd (M, N), is defined to be the positive integer D such that

    1. D divides N and M, and
    2. D is the largest integer dividing both N and M; i.e., every integer E that divides both N and M also divides D.

    For example, 2 = gcd (6, 8); 4 = gcd (4, 12); 1 = gcd (8, 9); 6 = gcd (66, 24).

    Algorithm: The algorithm proceeds by long division -- keeping track of subsequent remainders:

    This process continues until we find a remainder Ri+1 which is 0. Then Ri = gcd (M, N).


    1. Divide 66 by 24: remainder is 18.
    2. Divide 24 by 18: remainder is 6
    3. Divide 18 by 6: remainder is 0, so we can stop.

      Thus, 6 = gcd (66, 24).

    Write a C program that reads two positive integers from the keyboard and computes their greatest common divisor in two ways using the Euclidean Algorithm.

    The main program should read numbers m and n, call both functions, and print the results computed within each function. (Note that printing should NOT be done in the two functions, but rather in the main procedure.)



  1. Write a program to score a bowling game. Scoring details are available from Wikipedia under Ten-pin Bowling

    The program should ask the user to enter the number of pins hit by successive balls, tabulate the score frame-by-frame, and give the final score. In frames when a strike is thrown, the program should not ask for the pins hit by the second ball (as no ball is thrown). Also, if a spare or strike is thrown in the tenth frame, the program should ask for the correct number of bonus balls and compute the final total appropriately.

Emergency Telephones

  1. [This problem is inspired by Problem 3 on the 1985 Advanced Placement Computer Science Examination; folklore now sometimes refers to this exercise as "The Dreaded TelLocs Problem".]

    The arrangement of streets in many midwestern cities resembles a 2-dimensional grid. If emergency telephones are placed at the intersection of streets, then their location can be modeled by a 2-dimensional array:

        #define north_south_size 20
        #define east_west_size   25
        int tel_locs [north_south_size] [east_west_size];

    For this array, the location tel_locs[0][0] is considered to be in the southwestern corner of the grid; and the location tel_locs[1][2] has the location that is north 1 block and east 2 blocks of the southwestern corner of the grid.

    Within this array, tel_locs[i][j] is 1 if an emergency telephone is located at intersection of streets i and j, and tel_locs[i][j] is 0 otherwise.

    In a certain city, intersection [r][s] is considered "safe" if the [r][s] is within 2 blocks of an emergency telephone — moving north or west. Thus, (ignoring the edge of the array), [r][s] is "safe" if there is an emergency telephone at [r][s], [r+1][s], [r+2][s], [r][s-1], [r][s-2], or [r+1][s-1]. (Due to one-way streets, the notion of "safe" does not consider emergency telephones located to the south or east of intersections.)

    Write a C program that analyzes a proposed placement of emergency telephones in a city to determine if all intersections in the city can be considered "safe". The program should have these characteristics:

    1. The array tel_locs should be declared and initialized as part of the program. (You should not read in the placement of telephones; the program will have to be edited for each proposed telephone placement.)
    2. A function safe should take a location and a tel_locs array as parameters and return 1 or 0 if the location is "safe" or not (respectively).
    3. The program should print the coordinates of any intersection that is not "safe".
    4. The end of the program should indicate "all safe" if all intersections in the city are "safe" or "unsafe intersections exist" if there is at least one intersection that is not "safe".

Distance to Fire Hydrants

  1. Within cities, rates for property insurance often depend upon the distance between a house and the nearest fire hydrant. This problem outlines a simple version of this rather-general problem.

    Here are some details. We suppose that a city is organized as a grid of streets, and that fire hydrants are located near selected street intersections. The best insurance rates (category A) are available to houses who are at an intersection where there is also a fire hydrant. The second best insurance rates (category B) are available to houses at an intersection where the nearest fire hydrant is 1 block away (there is no fire hydrant at the house's intersection, but there is a fire hydrant 1 block away). The third best insurance rates (category C) are available to houses at an intersection where the nearest fire hydrant is 2 blocks away. The worst insurance rates (category D) are applied to houses for which there is no fire hydrant within 2 blocks (all hydrants are 3 or more blocks away).

    Of course, this problem is not unrelated to the Emergency Telephone problem (supplemental problem 3), with telephones replaced by fire hydrants and with searching possible in any direction. However, in this case, the issue is how close the nearest fire hydrant might be. Also, for this problem, the fire hydrant information will be located in a file.

    Additional details follow:

Word-Find Puzzle

  1. This exercise is based on a programming problem by Marge Coahran.

    This problem asks you to write a program that solves a "word-find" puzzle similar to puzzles that can be found in newspapers and magazines. An example is given below.

    The input data for your program will be a 16 x 16 grid of characters (the puzzle board) followed by a list of words. The object of the puzzle is to search the puzzle board for the words in the word list. Words may appear in the puzzle board horizontally or vertically (but not diagonally). Horizontal words will run left to right; vertical words will run top to bottom. Words will not "wrap around" in either direction, so for example, a word could not occupy columns {15,16,1,2}. Each word will appear at most once in the puzzle board.

    An example data file is available at /home/walker/161/problems/puzzleboard for your use, but your program should work on any input file that conforms to the following specifications.

    Puzzle Specifications

    The puzzle board will be given first. It will consist of a matrix of 16 x 16 upper-case letters, with a single space between each character on each row. Next the file will contain a list of upper-case words, each on a separate line, and each of which could fit within the puzzle board. The number of words is not specified, so your program should read until the end of the file is reached. There will be no blank lines anywhere in the file.

    Your program should specify the input file name as a command-line parameter, and the program should print the name of the file as part of its output.

    Your program should output a "key" to the word-find puzzle as shown in the example below. Essentially, the key is a copy of the puzzle board matrix that contains only the words which your program has found. All other characters of the board should be removed.

    Anti-hint: There are C library functions called strstr(), strchr(), and strrchr(), which you are NOT ALLOWED to use in this program. These functions would take away too much of your fun.

    Test Cases

    As part of your write up, please describe a set of cases that would be appropriate for testing this program. (Since designing these puzzles is non-trivial, you need not submit a puzzle of your own containing your tests, but describe what situations you would want to test.) It would also be wise of you to modify the example below if there are test cases missing from it, to allow you to thoroughly test your code.

    An (overly-simplified) list of test cases might look something like this:


    Consider the input:

    G R N L R S Y S T E M E E O M R
    O C O M P U T E R E H I A I C U
    R A I M P R O G R A M A N R R R
    Q M E M O R Y A N T C R N T T M
    L A O N E T W O R K R O H H E U
    G T R Y S T R I N G I A E G Q E
    R R R N E A N Y L Y I L E E U R
    T R P T A R E C O S S G I T A A
    R L T P A R N A G O M E R U T S
    E I H H T A G L I K L B S R I C
    N T E Y T Y I C C M C R M I O H
    Y R O S A H N U U G R A E D N E
    P G R I N N E L L U U C A R S M
    C G Y C E K E U R S S B A S L E
    C N S S R E R S O U R R T P R B
    C N P O C N R M R U A I G A S O

    When given this input, the program should print:

              S Y S T E M 
      C O M P U T E R 
            P R O G R A M 
      M E M O R Y
          N E T W O R K         E
            S T R I N G   A     Q
              A     L     L     U
              R   C O     G     A
        T P   R   A G     E     T S
        H H   A   L I     B     I C
        E Y   Y   C C     R     O H
        O S       U       A     N E
      G R I N N E L L             M
        Y C       U               E
          S       S

Any of the following problems may be done for extra credit. As noted in the course syllabus, however, a student's overall problems' average may not exceed 120%.

Common Letters

  1. Write a program that reads two strings and counts how many letters the strings have in common. To determine common letters, each letter of one word should be matched with exactly one letter of the second word. the case of the letters (upper case versus lower case) should be ignored.)


Recording and Retrieving Golf Scores

  1. The reading on doubly-linked lists presents this problem: "In recording scores for a golf tournament, we enter the name and score of the player as the player finishes. This information is to be retrieved in each of the following ways:

    This supplemental problem asks you to solve this problem using a doubly linked list. Some details follow.

    Note: This program may utilize any code developed in the lab for doubly-linked lists (with appropriate citation). Since that lab does not place nodes in order (menu option a) or move back and forth from a given node (menu option b), those parts of this problem should not be based on the collaborative lab.

Unusual Canceling

  1. The fraction 64/16 has the unusual property that its reduced value of 4 may be obtained by "canceling" the 6 in the numerator with that in the denominator. Write a program to find the other fractions whose numerators and denominators are two-digit numbers and whose values remain unchanged after "canceling."

    Of course, some fractions trivially have this property. For example, when numerator and denominator are multiples of 10, such as 20/30, one can always "cancel" the zeroes. Similarly, cancellation is always possible when the numerator and denominator are equal, as in 22/22. Your program should omit these obvious cases.

Roman Numerals

  1. Write a procedure that reads an integer N between 1 and 1000 from the keyboard and prints the Roman numerals between 1 and N in alphabetical order.

    Note: The Bubble Sort is not covered in this course, because it is never considered to be an acceptable algorithm.

Printing Cross Words

  1. Consider the problem of printing two words, the first word vertically (one letter per line) and the second word horizontally, so the words cross at a common letter. For example, if the first word is FUNCTIONAL and the second is SCHEME, then the desired output is:


    In this problem, you are to write a program that reads two words from a terminal window and prints them in the crossed pattern shown above (assuming they have a letter in common). If the words have more than one letter in common, then they may be printed with the crossing at any common letter. If the words have no letters in common, then the program should print an error message.

Dealing Bridge Hands

  1. Write a program that simulates the dealing of a deck of cards to give four bridge hands. The program should print both the cards held for each hand and the point-count for bidding.

    A simple scoring system gives an ace 4 points, a king 3 points, a queen 2 points, and a jack 1 point, with an extra point given if a hand contains all aces and a point deducted if it contains no aces. Points also are given for distribution, with a point given if a hand contains only 2 cards in a suit (a doubleton), 2 points given if a hand contains a single card in a suit (a singleton), and 3 points given if a hand has no cards in some suit.

Information on the 1997-1998 Iowa Senate

  1. File /home/walker/151s/labs/ia-senate contains information about the members of the 1997-1998 Iowa Senate. After a title line and a blank line, a typical line has the following form:
    Angelo          Jeff        44      Creston           IA 50801
    Kramer          Mary        37      West Des Moines   IA 50265
    Lundby          Mary        26      Marion            IA 52302-0563
    Thus, a typical line gives the last name, the first name, the district number, the town of residence, the state (always IA), and the town's zip code. The information in these lines is arranged in columns.

    Design and write a Scheme program that reads in data from this file and creates two output files, senators-by-district and senators-by-zip-code, in the current working directory. The senators-by-district file should contain the same data as the source file, in the same format, but with the lines arranged by senate district (column 3). The other file, senators-by-zip-code, should contain a list of all senators in the following format

    Jeff Angelo
    Creston, IA 50801
    A blank line should appear after each senator and city address. In this format, the name appears on a first line (first name, then last), and the city, a comma, the state, and zip code is on the next line -- separated by single spaces in the format shown. Note that a variation of this format (with a street address, if available) might be used for a mailing label.

File Analysis

  1. Write a C program that takes the name of a file as a command-line argument, opens the file, reads through it to determine the number of words in each sentence, displays the total number of words and sentences, and computes the average number of words per sentence. The results should be printed in a table (at standard output), such as shown below:

         This program counts words and sentences in file "comp.text ".
         Sentence:  1    Words: 29
         Sentence:  2    Words: 41
         Sentence:  3    Words: 16
         Sentence:  4    Words: 22
         Sentence:  5    Words: 44
         Sentence:  6    Words: 14
         Sentence:  7    Words: 32
         File "comp.text" contains 198 words words in 7 sentences
         for an average of 28.3 words per sentence.

    In this program, you should count a word as any contiguous sequence of letters, and apostrophes should be ignored. Thus, "word", "sentence", "O'Henry", "government's", and "friends'" should each be considered as one word.

    Also in the program, you should think of a sentence as any sequence of words that ends with a period, exclamation point, or question mark.

    Exception: A period after a single capital letter (e.g., an initial) or embedded within digits (e.g., a real number) should not be counted as being the end of a sentence.
    White space, digits, and other punctuation should be ignored.

Parenthesis Checking

  1. Write a program that reads a line of text from the terminal and checks if the parentheses in the line are balanced.


    1. The program should distinguish among three types of parentheses, { }, [ ], ( ).
    2. Parentheses checking should involve working from the inside of nested parentheses to the outside.
    3. In each case, the appropriate right parenthesis should be matched with a left parenthesis of the same type.


    1. ( these { parentheses[] match } perfectly ) !!!
    2. (the {right [parentheses ) on } this line ] are in the wrong order.
    3. this ( line { is missing } one (round ) right parenthesis.

    Comments on a solution to the problem: This problem can be solved reasonably easily using a single left-to-right scan of a line, if left parentheses are placed on a stack as they are encountered. Then, when a right parenthesis is found, the stack can be popped and one can check if the right parenthesis has the same type as the left one.

    Programming Note: Your program should use a self-contained Stack library package, as described in the lab on Stacks and Queues with Linked Lints and implemented as lists.

This document is available on the World Wide Web as

created 22 May 2008
last revised 8 November 2011
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at