CPSC 211, Sec 201-203
Spring 2004
Program 2: Implementing Fraction and MixedNumber ADTs in Java

INSTRUCTIONS

PURPOSE

The purpose is to practice more with abstract data types and a little with recursion. This assignment is taken from Data Structures and Abstractions with Java, by Frank M. Carrano and Walter Savitch, Prentice-Hall, 2003.

REQUIREMENTS

1. Write a specification of a class Fraction.

The state includes a numerator and a denominator, both of which are integers; negative fractions are possible. Be sure to handle zero denominators. A fraction should always be stored in lowest terms. Improper fractions are allowed (numerator > denominator).

Operations must include

• the binary operations add, subtract, multiply and divide. As is typical in object-oriented languages, for binary operation op, to compute f3 = f1 op f2, the syntax should be f3 = f1.op(f2).
• reciprocal
• compare two fractions
• toString

2. Implement your Fraction class in Java. Some hints follow.

To put a fraction in lowest terms, you need to compute the greatest common denominator of two integers. There is the famous Euclid's algorithm to do so:

```      gcd(a,b):
if (a mod b) = 0 then return b
else return gcd(b, a mod b)
```
Always store the denominator as a positive number.

3. Write a specification of a MixedNumber class.

The state contains an integer portion and a fractional portion. The fractional portion should be in lowest terms and have its numerator less than its denominator.

The operations should be analogous to those for the Fraction class.

4. Implement your MixedNumber class in Java.

Use the operations in Fraction whenever possible. For instance, to add two mixed numbers, convert them to fractions, add the fractions using the Fraction class add method, and then convert the result to mixed number form.

Watch out for problems with the sign. For instance, you don't want to print out -5 -1/2 (you should print either 5 1/2 or -5 1/2).

TURN-IN REQUIREMENTS

Due by 10:20 AM on Wednesday, Feb 18:

• Turn in your code using the "turnin" program in the CS department Unix machines. (Turnin instructions available here.)
• Turn in your paper specification documents, testing documentation and cover sheet in class.