Classes and Objects
Contents
Fraction Example (using struct)
main.cppx
using namespace std;
/**
* gcd(a, 0) = a
* gcd(a, b) = gcd(b, a mod b)
*/
int gcd(int a, int b)
{
if (b==0)
return a;
return gcd(b, a%b);
}
/**
* lcm = (a*b)/gcd(a,b)
*/
int lcm(int a, int b)
{
auto local_gcd = gcd(a,b);
if (local_gcd == 0)
return 0;
return a / gcd(a,b) * b;
}
struct Fraction
{
int numerator;
int denominator;
};
Fraction add_fractions(Fraction lhs, Fraction rhs)
{
auto common_den = lcm(lhs.denominator, rhs.denominator);
lhs.numerator = lhs.numerator * common_den/lhs.denominator;
rhs.numerator = rhs.numerator * common_den/rhs.denominator;
lhs.denominator = rhs.denominator = common_den;
Fraction sum;
sum.numerator = rhs.numerator + lhs.numerator;
sum.denominator = common_den;
return sum;
}
void display_fraction(const Fraction& f)
{
cout << f.numerator << "/" << f.denominator;
}
int main()
{
Fraction f1 = {1, 2};
Fraction f2;
f2.numerator = 1;
f2.denominator = 3;
Fraction sum = add_fractions(f1, f2);
display_fraction(f1);
cout << " + ";
display_fraction(f2);
cout << " = ";
display_fraction(sum);
cout << endl;
return 0;
}
Fraction Example (using class)
main.cpp// compilation command:
// g++ -std=c++11 -o prog fraction.cpp main.cpp
using namespace std;
int main()
{
Fraction f1(1, 3);
Fraction f2(2, 3);
Fraction sum = f1.add_fractions(f2);
f1.display();
cout << " + ";
f2.display();
cout << " = ";
sum.display();
cout << endl;
return 0;
}
class Fraction
{
public:
Fraction(int num, int den);
Fraction add_fractions(Fraction rhs);
void display();
private:
int numerator;
int denominator;
};
using namespace std;
/**
* gcd(a, 0) = a
* gcd(a, b) = gcd(b, a mod b)
*/
int gcd(int a, int b)
{
if (b==0)
return a;
return gcd(b, a%b);
}
/**
* lcm = (a*b)/gcd(a,b)
*/
int lcm(int a, int b)
{
auto local_gcd = gcd(a,b);
if (local_gcd == 0)
return 0;
return a / gcd(a,b) * b;
}
Fraction::Fraction(int num, int den)
{
numerator = num;
denominator = den;
}
Fraction Fraction::add_fractions(Fraction rhs)
{
Fraction lhs(numerator, denominator);
auto common_den = lcm(lhs.denominator, rhs.denominator);
lhs.numerator = lhs.numerator * common_den/lhs.denominator;
rhs.numerator = rhs.numerator * common_den/rhs.denominator;
lhs.denominator = rhs.denominator = common_den;
Fraction sum(1, 1);
sum.numerator = rhs.numerator + lhs.numerator;
sum.denominator = common_den;
return sum;
}
void Fraction::display()
{
cout << numerator << "/" << denominator;
}