create a dynamic array of the fraction object

I wrote a program for fraction addition. However I need to input the 3 parts of the fraction into a dynamic array rather than the way it is now. Anyone could help to edit the code?

BTW The code must keep the following part.
class fraction
{
public:
fraction();
void read();
void print();
friend fraction operator +(fraction, fraction); //fraction add

private:
int integral, numerator, denominator;
}




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>

using namespace std;

int gcd(int a,int b)
{
    if(b==0)
        return a;
    return gcd(b,a%b);
}
class fraction
{
public:
    fraction() //constructor for initialize
    {
        integral=0,numerator=0,denominator=0;
    }
    void read(int a,int b,int c) //read 3 int from keyboard for the fraction
    {
        integral=a;
        numerator=b;
        denominator=c;
    }
    void print()//print the fraction on screen
    {
        if(integral==0)
        {
            cout<<"Their sum is "<<"{"<<numerator<<"/"<<denominator<<"}";
        }
        else
        {
            cout<<"Their sum is "<<integral<<"{"<<numerator<<"/"<<denominator<<"}";
        }
    }
    friend fraction operator +(fraction i, fraction j); //fraction add
private:
    int integral, numerator, denominator;
};
fraction operator +(fraction i, fraction j)
{
    fraction temp;
    int g;
    temp.numerator=(i.numerator*j.denominator+i.denominator*j.numerator);
    temp.denominator=i.denominator*j.denominator;
	temp.integral=i.integral+j.integral;
    g=gcd(temp.numerator,temp.denominator);
	
    temp.numerator/=g;
    temp.denominator/=g;
	temp.integral+=(temp.numerator/temp.denominator);
	temp.numerator%=temp.denominator;
    return temp;
}

int main()
{
    int n;
    fraction sum,temp;
    cout<<"Enter number of fractions:"<<endl;
    cin>>n;
    int a,b,c;
    for(int i=1;i<=n;i++)
    {
        cout<<"Enter fraction "<<i<<":"<<endl;
        cin>>a>>b>>c;
        if(i==1)
        {
            sum.read(a,b,c);
        }
        else
        {
            temp.read(a,b,c);
            sum=sum+temp;
        }
		//cout<<endl;
    }
	sum.print();

    return 0;
}
Last edited on
Topic archived. No new replies allowed.