Fraction Calculator Assignment

CSC 7000-002 Algorithms & Programming
Fall 1999, Mendel 115
Dr. David Matuszek

The idea of this assignment is to write a calculator for fractions. The purpose of this assignment is to get you to use structs, and to give you more practice with string manipulation and functions.

Define a struct named fraction, with int fields numer (for numerator, the number above the line) and denom (for denominator, the number below the line).

You should treat every number as a pure fraction; for example, 5 would be 5/1, and 2 3/4 would be 11/4. All fractions should be in lowest terms, for example, 5/10 should be replaced by 1/2. The denominator should always be a positive integer; if a fraction is negative, use a negative numerator, for instance -5/3.

Your program should behave like a normal inexpensive calculator, in that it keeps track of only one number at at time; but in this case the number will be a fraction. It should support the following operations: e (enter, that is, replace the previous number), + (add), - (subtract), * (multiply), and / (divide). As you use the program, your output should look something like this:

You type:  Computer responds:
e 6/24
1/4
+ 1/2
3/4
/ 3/-4
-1/1
e 7/-8
-7/8

In case you've forgotten how to do arithmetic with fractions:

n1/d1 + n2/d2 = (n1*d2 + n2*d1) / (d1*d2)
n1/d1 - n2/d2 = (n1*d2 - n2*d1) / (d1*d2)
n1/d1 * n2/d2 = (n1*n2) / (d1*d2)
n1/d1 / n2/d2 = (n1*d2) / (d1*n2)

You should have a separate function for each of these four operations; each function should take two "fractions" as arguments and produce a "fraction" as a result. Write functions to read and to write fractions. In addition, write one or two functions to normalize (adjust) any result, including the result of an "enter" operation, so that (1) the denominator is positive, and (2) the fraction is in lowest terms. Hint: we discussed Euclid's algorithm in the first class: to get the greatest common divisor of two integers, repeatedly subtract the smaller from the larger until the two are equal.

You will find the function int atoi(const char *s), for converting strings to integers, very helpful. (It is discussed in your textbook.)

Turn in a listing of your program along with a sample transcript of using the program. The transcript should clearly show that your program works for all operations and that it properly normalizes all results.