Next Exercise | Lecture | Solution | Top Level

Creating the Dice class

The following exercises will basically follow the pattern set by the lecture. At every step, compile and test your programs and proceed to the next step only if you are sure you got it right.

  1. Write a C program that prints out a random number between one and six. Look up documentation on library functions (man rand) on how to do it. Note that the rand function is pretty bad - you might want to think about improving it

  2. Modify the program do generate a monopoly die roll. The output should consist of the sum of the two dice and the word "pair" if the roll was a pair. Hint: write a function that will return a random value between 1 and 6, and use that function twice.

  3. Modify the program so that the current die roll is stored in a structure. Write a function Roll that will roll the dice, a function Total that returns an integer value, and a function Pair that returns 1 if the roll was a pair, 0 otherwise, and finally, a function Read and Write that will read from standard input and write to standard output the contents of the structure.

  4. Split your program file into 3 parts, creating a Dice module: The resulting program should read values for the structure (the old die roll), use the functions Total and Pair, use Roll to generate new values and Write out the new values.

    Note that we have to capitalize Read and Write to avoid confusion with the system calls read and write.

    Use the following commands to compile this program (you might want to write a shell script or a Makefile):

       % gcc -c dice.c
       % gcc -c main.c
       % gcc -o main main.o Dice.o
       

  5. Rewrite as a C++ program: merge the structure and the functions into a class. The functions will become public member functions, and the data stored in the structure will become private data. To distinguish from the old C programs, C++ programs use the extension .C. You might also want to call the three files Dice.h, Dice.C and Main.C to avoid clobbering your old files.

    Note that in C++, we do not have to worry about name conflicts anymore, as we now use member functions.

    Remember to use g++ to compile...