Programming in C, autumn 2008


Exercise 3

MON Sep. 22 12:15-15:00 BK106

  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 which has one integer parameter n, and which prints the Pascal triangle for any n > 0; for example, for n=4, the function prints:
    1       1
    1       2       1
    1       3       3       1
    1       4       6       4       1
    
    Write also a main program, which you can use to test the function.

  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).