Programming in C, autumn 2010


Exercise 3

THU Sep. 23 9:15-12:00 B119 summary lecture and exercises

  1. Suppose, that MIN is a macro, defined like this:
    #define MIN(x,y)   x < y ? x : y
    
    Show the fully expanded form of the following expressions and calculate the values of these expressions:
    1 + MIN(2,3)
    1 + MIN(3,2)
    MIN(2,3) + 1
    MIN(3,2) + 1
    
    Write a macro MED(a,b,c), which prints 1 if the value of b is between a and c; otherwise it prints 0. Assume a, b, c are integers.

    Write a macro OPEN(f), which opens file f for reading using "junk" as the filename. Evaluates to 1 if successful; 0 otherwise.

  2. Write a program that merges two files containing sorted lists of double values; the output file should contain a sorted list; for example, given the following two input files:
    1.2     3.4     6
    2.4     5       9
    
    the output file would contain:
    1.2     2.4     3.4     5       6       9
    
    Use conditional compiling and change the program so that in a debugging mode, the program displays a message informing the user as from which input file is being read, if the reading is not successful.

  3. Write a function findSum(), which has two integer parameters n and m, and returns the sum of all the integers from n up to m (inclusive). Write also a main program, which you can use to test the function.

  4. Write a function that takes the time as three integer arguments (for hours, minutes, and seconds), and returns the number of seconds since the last time the clock "struck 12". Use this function to calculate the amount of time in seconds between two times, both of which are within one 12-hour cycle of the clock.
  5. The Towers of Hanoi.

    According to an ancient legend, God, when creating the world, placed three diamond needles standing in an Asian temple. Ever since then, priests are attempting to move a stack of golden disks from one needle to another. The initial stack had 64 disks threaded onto one needle (A) and arranged from bottom to top by decreasing size. The priests are attempting to move the stack of disks from the needle A to another needle B using a third needle C. The following rules restrict the moving: According to the legend, the World will end when the priests have moved all disks to needle B.

    Write a recursive program, which gives advice on how to move disks using following commands:
    Move a disk from the needle A to the needle B.
    Test your program using a small number of disks (4-10).
Study also
  1. Memory management
  2. Look at generic functions