Homework  10 Solution

Write a program that reads in two fractions from the user and prints out the sum of the two numbers in lowest terms. Recall (from grade school!) that

`n1    n2     n1 d2 + n2 d1`
`-- +  --  =  -------------`
`d1    d2         d1 d2`

and that to reduce a fraction to lowest terms you divide the numerator n and the denominator d by the greatest common divisor of n and d. Of course, in these lecture notes we discuss greatest common divisor! A run of your program should look something like this:

 `Enter a fraction addition problem: 15/28 + 7/32``15/28 + 7/32 = 169/224`

Turn In a printout of your code, along with a screen capture of your program running on input `15/28 + 7/32`.

Solution

// KGS
// Hmwk 10

#include <iostream>
using namespace
std;

int main(){
int numerator1, numerator2, denominator1, denominator2;
char junk;

cout << "Enter a fraction addition problem: ";
cin >> numerator1 >> junk >> denominator1 >> junk >> numerator2 >> junk >> denominator2;

int ansNumerator,ansDenominator;
ansNumerator = numerator1*denominator2 + numerator2*denominator1;
ansDenominator = denominator1*denominator2;

int a, b, r;
// Make sure a contains the larger of the two numbers
if (ansNumerator >= ansDenominator) {
a = ansNumerator;
b = ansDenominator;
}
else {
a = ansDenominator;
b = ansNumerator;
}

// Find the gcd
while (b != 0){
r = a % b; // remember "%" is remainder
a = b;
b = r;
}

// Reduce the fraction
// Note variable a contains the gcd
ansNumerator = ansNumerator/a;
ansDenominator = ansDenominator/a;

// Print the results
cout << endl << numerator1 << '/' << denominator1 << " + " << numerator2 << '/' << denominator2
<< " = " << ansNumerator << '/' << ansDenominator << endl;
return 0;
}