CS 102 Laboratory Session Three

Week Four Lab session. This lab session continues using the fraction class from last week. Thanks again to Claire Bono for creating these exercises. Used with permission.

Exercise One

Two checkoff points.

Make a copy of the correct version of the program and call it ex2.cc.

1. Figure out which of the following operations are legal on Fraction objects by modifying your program so that it tries to use each on Fractions:

2. Eliminate the illegal operations from your program. Change your program so it demonstrates whether parameter passing works by value (like ints do in C and C++) or by reference (like arrays do in C and C++). Note: this question does not concern reference parameters, but rather the behavior of regular parameters (i.e., no & or * are involved).

For checkoff, give the answers to (1) above; show your changes to the program for (2); and show and explain the results of running it with those changes.

Exercise Two

Three checkoff points.

1. Start with a copy of the correct version of the program.

2. Write a function that takes a positive integer n, computes the following sum, and returns it as a Fraction:

1/1 + 1/2 + 1/4 + . . . + 1/2n

That is, it will return an exact value, not a decimal approximation. Your function must use a loop -- not a closed form solution. Also, do not use any functions from the math library.

Here is the header for the function (a "shell" of the function appears in fractlab.cc):

Fraction sumOfFracts(int n);

3. Test your function by writing a simple main program that prompts for n (no error checking necessary), prints out the resulting sum as a fraction, and also prints out a decimal (i.e., floating point) approximation of the Fraction returned by your function.

4. Test your program on some numbers. At what values does it start getting the wrong answer because of overflow problems?

5. Ignoring our overflow problems (i.e., just considering the smaller numbers), what value is the series converging on? (what number does the sum approach for very large n)

6. For checkoff, show the t.a. your function working on small numbers and give the answers to the two questions above.



This page established September 12, 1999; last updated September 12, 1999 by Rick Wagner.