FRACTION MANIPULATION USING OPERATOR OVERLOADING

Aim:
            To write a program in c++ for fraction manipulation using operator overloading.

Algorithm:
Step 1:start the process.
Step 2:declare a class fract.
Step 3: declare the constructor fract and fract(int n,int d).
Step 4:declare the function such as void read() void Tostring().
Step 5:enter the choice for:
1. Addition
2. Subtraction
                                                            3. Multiplication
4. Division.
5. Comparing

Step 6: get the choice from the user and do the required calculation or operation.
Step 7: print the output ,save the program and exit.


PROGRAM CODE:
#include<iostream.h>
class fract
{
int num,den;
public:
fract()
{
num=0;
den=1;
}
fract(int n,int d)
{
num=n;
den=d;
}
void read()
{
cin>>num>>den;
}
fract reduce()
{
fract t(0,1);
int i,d=1,min;
min=(num<den?num:den);
for(i=1;i<=min;i++)
{
if(num%i==0&&den%i==0)
d=i;
}
t.num=num/d;
t.den=den/d;
return t;
}
fract operator +(fract a)
{
fract ans(0,1);
ans.den=den*a.den;
ans.num=num*a.den+a.num*den;
return ans;
}
fract operator -(fract a)
{
fract ans(0,1);
ans.den=den*a.den;
ans.num=num*a.den-a.num*den;
return ans;
}
fract operator *(fract a)
{
fract ans(0,1);
ans.num=num*a.num;
ans.den=den*a.den;
return ans;
}
fract operator /(fract a)
{
fract ans(0,1);
ans.num=num*a.den;
ans.den=a.num*den;
return ans;
}
int operator >(fract a)
{
fract b(0,1),c(0,1);
b.num=num*a.den;
c.num=a.num*den;
if(b.num>c.num)
return 1;
else
return 0;
}
int operator <(fract a)
{
fract b(0,1),c(0,1);
b.num=num*a.den;
c.num=a.num*den;
if(b.num<c.num)
return 1;
else
return 0;
}
int operator ==(fract a)
{
fract b(0,1),c(0,1);
b.reduce();
c.reduce();
if(b==c)
return 1;
else
return 0;
}
void Tostring()
{
cout<<num<<"/"<<den;
}
};
main()
{
fract x,y,z;
int d;
char c;
do
{
cout<<"\nFraction manipulation";
cout<<"\n The choices are:";
cout<<"\n1.Addition\n2.Substraction\n3.Multiplication\n4.Division\n5.Comparing\n6.Quit\n";
cout<<"Enter your choice:";
cin>>d;
if(d<7)
{
cout<<"Enter the fractional numbers:";
x.read();
y.read();
}
switch(d)
{
case 1:
z=x+y;
z=z.reduce();
cout<<"\n";
x.Tostring();
cout<<"+";
y.Tostring();
cout<<"=";
z.Tostring();
break;
case 2:
z=x-y;
z=z.reduce();
cout<<"\n";
x.Tostring();
cout<<"-";
y.Tostring();
cout<<"=";
z.Tostring();
break;
case 3:
z=x*y;
z=z.reduce();
cout<<"\n";
x.Tostring();
cout<<"*";
y.Tostring();
cout<<"=";
z.Tostring();
break;
case 4:
z=x/y;
z=z.reduce();
cout<<"\n";
x.Tostring();
cout<<"/";
y.Tostring();
cout<<"=";
z.Tostring();
break;
case 5:
if(x>y)
{
x.Tostring();
cout<<">";
y.Tostring();
}
else if(x==y)
{
x.Tostring();
cout<<"==";
y.Tostring();
}
else
{
x.Tostring();
cout<<"<";
y.Tostring();
}
case 6:
exit(0);
break;
}
cout<<"\nDo you want to continue(y/n)";
cin>>c;
}while(c=='y'||c=='Y');
}

0 comments: