Here are C++ programs to subtract two fractions. First program subtract two fractions using for-loops, and second program uses operator overloading.
C++ program subtract two fractions using for-loops
#include<iostream>
using namespace std;
int main()
{
int a1,a2,b1,b2,c1,c2,lcm=1,grtr,d2,e2;
cout<<"Enter the first fraction number ";
cin>>a1>>a2;
cout<<"Enter the second fraction number ";
cin>>b1>>b2;
d2=a2,e2=b2;
if(a2>b2)
grtr=a2;
else
grtr=b2;
for(int i=2;i<=grtr;i++)
{
while(a2%i==0||b2%i==0)
{
if(a2%i==0)
a2=a2/i;
if(b2%i==0)
b2=b2/i;
lcm*=i;
}
}
c1=(a1*(lcm/d2))-(b1*(lcm/e2));
c2=lcm;
cout<<"subtraction of two fraction ="<<c1<<"/"<<c2;
return 0;
}
using namespace std;
int main()
{
int a1,a2,b1,b2,c1,c2,lcm=1,grtr,d2,e2;
cout<<"Enter the first fraction number ";
cin>>a1>>a2;
cout<<"Enter the second fraction number ";
cin>>b1>>b2;
d2=a2,e2=b2;
if(a2>b2)
grtr=a2;
else
grtr=b2;
for(int i=2;i<=grtr;i++)
{
while(a2%i==0||b2%i==0)
{
if(a2%i==0)
a2=a2/i;
if(b2%i==0)
b2=b2/i;
lcm*=i;
}
}
c1=(a1*(lcm/d2))-(b1*(lcm/e2));
c2=lcm;
cout<<"subtraction of two fraction ="<<c1<<"/"<<c2;
return 0;
}
C++ program subtract two fractions using operator overloading
#include<iostream>
using namespace std;
struct frac{
int a1,a2;
};
frac operator -(frac a,frac b)
{
frac c;
int d2=a.a2,e2=b.a2,grtr,lcm=1;
if(a.a2>b.a2)
grtr=a.a2;
else
grtr=b.a2;
for(int i=2;i<=grtr;i++)
{
while(a.a2%i==0||b.a2%i==0)
{
if(a.a2%i==0)
a.a2=a.a2/i;
if(b.a2%i==0)
b.a2=b.a2/i;
lcm*=i;
}
}
c.a1=(a.a1*(lcm/d2))-(b.a1*(lcm/e2));
c.a2=lcm;
return c;
}
int main()
{
frac a,b,c;
cout<<"Enter the first fraction number ";
cin>>a.a1>>a.a2;
cout<<"Enter the second fraction number ";
cin>>b.a1>>b.a2;
c=a-b;
cout<<"subtraction of two fraction ="<<c.a1<<"/"<<c.a2;
return 0;
}
using namespace std;
struct frac{
int a1,a2;
};
frac operator -(frac a,frac b)
{
frac c;
int d2=a.a2,e2=b.a2,grtr,lcm=1;
if(a.a2>b.a2)
grtr=a.a2;
else
grtr=b.a2;
for(int i=2;i<=grtr;i++)
{
while(a.a2%i==0||b.a2%i==0)
{
if(a.a2%i==0)
a.a2=a.a2/i;
if(b.a2%i==0)
b.a2=b.a2/i;
lcm*=i;
}
}
c.a1=(a.a1*(lcm/d2))-(b.a1*(lcm/e2));
c.a2=lcm;
return c;
}
int main()
{
frac a,b,c;
cout<<"Enter the first fraction number ";
cin>>a.a1>>a.a2;
cout<<"Enter the second fraction number ";
cin>>b.a1>>b.a2;
c=a-b;
cout<<"subtraction of two fraction ="<<c.a1<<"/"<<c.a2;
return 0;
}
No comments:
Post a Comment