Sum of fractions

This is a programme for adding up fractions.
I am required to use a dynamic array to store the fractions.
I have tried to run this programme, and it works for a dynamic array of size up to 4. However it crashes when 5 fractions are input.
Can anyone help me?
Thanks a lot! :)))))
the gcd function is for finding the greatest common divisor.

#include<iostream>
using namespace std;
class fraction
{
public:
fraction(); //constructor for initialize
void read(); //read 3 int from keyboard for the fraction
void print(); //print the fraction on screen
friend fraction operator +(fraction, fraction); //fraction add
private:
int integral, numerator, denominator;
};

fraction::fraction()
{integral=0;numerator=0;denominator=0;}

void fraction::read()
{
cin>>integral>>numerator>>denominator;
return;
}

int gcd(int a,int b)
{
if (a==b)
return b;
if (a>b)
{a = a-b;gcd(a,b);}
if (b>a)
{b = b-a;gcd(a,b);}
}

fraction operator +(fraction A, fraction B)
{
fraction temp;
temp.integral = A.integral + B.integral;
temp.numerator = A.numerator*B.denominator+A.denominator*B.numerator;
temp.denominator = A.denominator*B.denominator;
int divisor = gcd(temp.numerator,temp.denominator);
temp.numerator = temp.numerator/divisor;
temp.denominator = temp.denominator/divisor;
if (temp.numerator == temp.denominator)
{temp.numerator=0;temp.denominator=0;temp.integral++;}
if (temp.numerator>temp.denominator)
{temp.numerator=temp.numerator%temp.denominator; temp.integral++;}
return temp;
}

void fraction::print()
{
if(numerator==0)
cout<<integral;
else
cout<<integral<<"{"<<numerator<<"/"<<denominator<<"}"<<endl;
return;
}

int main()
{
cout<<"Enter number of fractions: \n";
int array_size;
cin>>array_size;
fraction *p = new fraction[array_size];
int n;
for(n=0;n<array_size;n++)
{
cout<<"Enter fraction "<<n+1<<":\n";
p[n].read();
}
fraction sum=p[0];
for(n=1;n<array_size;n++)
sum = sum+p[n];
cout<<"Their sum is: \n";
sum.print();
return 0;
}
Last edited on
Works fine for me with GNU GCC compiler and codeblocks.
Topic archived. No new replies allowed.