In the first class, after some administrivia, we looked at the definition
of "Abstract Data Type" (ADT) and gave some examples.  We gave an
overview of the course, then began looking at Rational number ADT as our
investigation into C++.


RATIONAL ADT A. The elements of the Rational ADT are rational numbers. The numerator and denominator components are of type "int". The denominator may not be zero. B. The following operations can be performed on Rational numbers 1. multiplication --- R1 * R2 2. addition -- R1 + R2 3. set the value of the numerator 4. retrieve the value of the numerator 5. etc.
Rational ADT - First Implementation Use a 'C' structure to hold the data and access the data directly as structure members. #include struct Rational { int num; int den; }; main () { Rational x, y, z; x.num = 5; x.den = 9; y.num = 3; y.den = 4; // z = x * y z.num = x.num * y.num; z.den = x.den * y.den; printf ("%d / %d\n", z.num, z.den); } NOTE: 1. printf works but is archaic -- more on this later 2. note the C++ comment style
Rational ADT - version 2 Use functions to manipulate the data in the structure void multiplyRational (Rational *z, Rational x, Rational y) { z->num = x.num * y.num; z->den = x.den * y.den; } void setRational (Rational *r, int n, int d) { r->num = n; r->den = d; } void printRational (Rational r) { printf ("%d / %d", r.num, r.den); } //--------------------------------- // Our main program becomes //------------------------------- main () { Rational x, y, z; setRational (&x, 5, 9); setRational (&y, 3, 4); multiplyRational (&z, x, y); printRational (z); }