reducing fraction

hello, I am writing a c++ program to reduce/simplify a fraction 21/14 -> 3/2.
I have to use struct Fraction and write 3 functions enter(&fraction),simplify(&fraction) display(fraction). I have to pass by address of an instance of a Fraction type in a pointer parameter for enter() and simplify. Here is the program I managed to write. It works. I want to know is there any way I can improve or any errors. Thanks!

--------------------------------------------------------------------------------

#include <iostream>

using namespace std;

struct Fraction {
int numerator;
int denominator;
};

struct Fraction enter (struct Fraction* f);
struct Fraction simplify (struct Fraction* f);
struct Fraction display (struct Fraction f);

int main(){

struct Fraction f;

enter(&f);

simplify(&f);

display(f);

return 0;
}

struct Fraction enter (struct Fraction* f){
cout << "Fraction Simplifier" << endl;
cout << "-------------------" << endl;
cout << "Numerator: ";
cin >> f->numerator;
cout << "Denominator: ";
cin >> f->denominator;
}

struct Fraction simplify (struct Fraction* f){

int k, i;

if(f->numerator < f->denominator)
k = f->denominator;
else
k = f->numerator;

for (i = k; i > 0; i--){
if(f->numerator % i == 0 && f->denominator % i == 0){
f->numerator = f->numerator / i;
f->denominator = f->denominator / i;
}
}
}

struct Fraction display (struct Fraction f){

cout << f.numerator << "/" << f.denominator <<endl;

}

I think you could break/exit out of the loop once you've found the greatest common divisor(gcd), because every other common divisor should be contained in the gcd. So you're not doing any unnecessary work.

Also don't your enter, simplify and display functions return Fraction structs, in which case how does it compile when you never return anything in any of those functions
In your iteration you could skip from the smallest of the two numbers to half of it, thereby saving half of the loop cycles.
Last edited on
closed account (3TXyhbRD)
For GCD: http://en.wikipedia.org/wiki/Euclidean_algorithm
Also, use code tags.
Topic archived. No new replies allowed.