Here is my solution, with the Fraction.h and Fraction.m files included.
/*
Exercise 15.7
Using the Fraction class defined in Part I, set up an array of fractions
with some arbitrary values. Then write some code that finds the sum of all
the fractions stored in the array.
*/
#import <Foundation/NSArray.h>
#import "Fraction.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Initialize 4 fractions with values and initialize sum to 0/1
Fraction
*f1 = [[Fraction alloc] init: 2:3],
*f2 = [[Fraction alloc] init: 3:5],
*f3 = [[Fraction alloc] init: 1:8],
*f4 = [[Fraction alloc] init: 9:5],
*sum = [[Fraction alloc] init: 0:1];
// Set up an array with the 4 Fractions (nil indicates the end of the list)
NSArray *fArray = [NSArray arrayWithObjects: f1, f2, f3, f4, nil];
// Define a Fraction object for fast enumeration over the Fraction array
Fraction *fObject;
// do fast enumeration over the Fraction array
// use a temporary Fraction to hold the result of add: in enumeration
for (fObject in fArray)
{
Fraction *temp = [sum add: fObject];
[sum setTo: temp.numerator over: temp.denominator];
[temp release];
}
[sum print];
[f1 release]; [f2 release]; [f3 release]; [f4 release];
[sum release];
[pool drain];
return 0;
}
//
// Fraction.h
// Exercise 15.7
//
#import <Foundation/NSObject.h>
@interface Fraction : NSObject {
int numerator;
int denominator;
}
@property int numerator, denominator;
-(id) init: (int) a : (int) b;
-(void) setTo: (int) a over: (int) b;
-(void) print;
-(double) convertToNum;
-(void) reduce;
-(Fraction *) add: (Fraction *) f;
@end
//
// Fraction.m
// Exercise 15.7
//
//
#import "Fraction.h";
@implementation Fraction
@synthesize numerator, denominator;
-(id) init: (int) a : (int) b
{
self = [super init];
if (self)
[self setTo: a over: b];
return self;
}
-(id) init
{
return [self init: 0 : 1];
}
-(void) setTo: (int) a over: (int) b
{
numerator = a;
denominator = b;
self.reduce;
}
-(void) print
{
if ( denominator < 0)
NSLog (@"%i/%i", -numerator, -denominator);
else
NSLog (@"%i/%i", numerator, denominator);
}
-(double) convertToNum
{
if ( denominator == 0 ) {
NSLog (@"division by zero");
return 0.0;
}
else
return (double) numerator / denominator;
}
-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;
while ( v != 0 )
{
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /= u;
}
-(Fraction *) add: (Fraction *) f
{
Fraction *result = [[Fraction alloc] init];
// (a/b) + (c/d) = ( (a*d) + (c*b) ) / (b * d)
result.numerator = numerator * f.denominator + f.numerator * denominator;
result.denominator = denominator * f.denominator;
self.reduce;
return result;
}
@end