Friday, January 5, 2018

Programming Challenge 14.13 - Carpet Calculator

Example Files: CarpetCalculator.7z

Note: Since the only addition to the FeetInches.h and FeetInches.cpp files written for Programming Challenge 14.11 is a conversion function that converts a FeetInches object to a double, there is no listing published for both of these files here.

RoomDimension.h


#ifndef ROOM_DIMENSION_H_
#define ROOM_DIMENSION_H_

#include "FeetInches.h"

class RoomDimension
{
    private:
        FeetInches width;
        FeetInches length;
   
    public:
        RoomDimension() {}

        RoomDimension(FeetInches w, FeetInches l) : width(w), length(l)
        {
        }

        FeetInches calcArea()
        {
            return width.multiply(length);
        }
};

#endif

RoomCarpet.h


#ifndef ROOM_CARPET_H_
#define ROOM_CARPET_H_

#include "RoomDimension.h"

class RoomCarpet
{
    private:
        RoomDimension dimension;

        double sqFtPrice;                // The cost per square footage of carpeting
        double totalCost;                // The total cost of a carpet

    public:
        RoomCarpet(RoomDimension dim, double price = 0.0) : dimension(dim), sqFtPrice(price)
        {
            calcTotalCost();
        }

        void calcTotalCost()
        {   
            totalCost = (dimension.calcArea()) * sqFtPrice;
        }
       
        double getTotalCost() const
        { return totalCost; }
};

#endif

CarpetCalculatorDm.cpp


#include "RoomCarpet.h"

#include <iomanip>
using std::setprecision;

#include <iostream>
using std::fixed;
using std::cin;
using std::cout;

int main()
{
    double price = 0.0;
    char choice = ' ';

    FeetInches width, length;

    cout << "WESTFIELD CARPET COMPANY - CARPET CALCULATOR\n\n";

    do
    {
        cout << "Please enter the width of your room:\n";
        cin >> width;
        cout << "\nPlease enter the length of your room:\n";
        cin >> length;

        RoomDimension dim(width, length);

        cout << "\nPlease enter the price per square yard: $ ";
        cin >> price;

        RoomCarpet purchase(dim, price);

        cout << setprecision(2) << fixed;
        cout << "\nThe total price of your "
              << width << " by " << length << " carpet is $ "
              << purchase.getTotalCost() << "\n\n";

        cout << "Do you wish to calculate the price for another room? ";
        cin >> choice;

        while (toupper(choice) != 'Y' && toupper(choice) != 'N')
        {
            cout << "Do you wish to calculate the price for another room? ";
            cin >> choice;
        }

        if (toupper(choice) == 'N')
        {
            cout << "\nThe Westfield Carpet Company thanks you for your patronage.";
        }
        cout << "\n";

    } while (toupper(choice) != 'N');

    cin.get();
    cin.ignore();
    return  0;
}

Example Output:



Thursday, January 4, 2018

Programming Challenge 14.12 - LandTract Class

Example Files: LandTractClass.7z

FeetInches.h


#ifndef FEET_INCHES_H_
#define FEET_INCHES_H_

#include <iostream>
using std::istream;
using std::ostream;

class FeetInches
{
    private:
        int feet;                        // To hold a number of feet
        int inches;                        // To hold a number of inches

        void simplify();                // Defined in FeetInches.cpp

    public:
        FeetInches(int f = 0, int i = 0)
        {
            feet = f;
            inches = i;
            simplify();
        }

        // Copy Constructor
        FeetInches(const FeetInches &obj)
        {
            feet = obj.feet;
            inches = obj.inches;
        }

        // Mutator functions
        void setFeet(int f)
        {
            feet = f;
        }

        void setInches(int i)
        {
            inches = i;
             simplify();
        }

        // Accessor functions
        int getFeet() const
        { return feet; }

        int getInches() const
        { return inches; }

        // Friends
        friend ostream &operator << (ostream &, const FeetInches &);
        friend istream &operator >> (istream &, FeetInches &);
};

#endif

FeetInches.cpp


#include "FeetInches.h"

#include <cstdlib>

#include <iostream>
using std::cout;

/* **********************************************************
            FeetInches::simplify()
    This function checks for values in the inches member
    greater than twelve or less than zero. If such a value is
    found, the numbers in feet and inches are adjusted to
    conform to a standard feet & inches expression. For
    example:

    3 feet 14 inches would be adjusted to 4 feet 2 inches and
    5 feet -2 inches would be adjusted to 4 feet 10 inches.

    The standard library function abs() is used to get the
    absolute value of the inches member. The abs() function
    requires to #include <cstdlib>.
   ********************************************************** */

void FeetInches::simplify()
{
    if (inches >= 12)
    {
        feet += (inches / 12);
        inches = inches % 12;
    }
    else if (inches < 0)
    {
        feet -= ((abs(inches) / 12) + 1);
        inches = 12 - (abs(inches) % 12);
    }
}

/* **********************************************************
            Overloaded << operator
    Gives cout the ability to directly display FeetInches
    objects.
   ********************************************************** */

ostream &operator << (ostream &strm, const FeetInches &obj)
{
    strm << obj.feet << " feet, " << obj.inches << " inches.";

    return strm;
}

/* **********************************************************
            Overloaded >> operator
    Gives cin the ability to directly store user input into
    FeetInches objects.
   ********************************************************** */

istream &operator >> (istream &strm, FeetInches &obj)
{
    // Prompt the user for the feet
    cout << "Feet: ";
    strm >> obj.feet;

    // Prompt the user for the inches
    cout << "Inches: ";
    strm >> obj.inches;

    // Normalize the values
    obj.simplify();

    return strm;
}

LandTract.h


#ifndef LAND_TRACT_H_
#define LAND_TRACT_H_

#include "FeetInches.h"

class LandTract
{
    private:
        int area;

        FeetInches width;
        FeetInches length;

    public:
        LandTract(FeetInches w, FeetInches l) : width(w), length(l)
        {
            area = 0;
            calcArea();
        }

        void calcArea();

        int getArea() const
        { return area; }

        // Overloaded operator
        bool operator == (const LandTract &);                    // Overloaded ==
};

#endif

LandTract.cpp


#include "LandTract.h"

/* **********************************************************
            LandTract::calcArea()
    Calculates the area of two tracts of land.
   ********************************************************** */

void LandTract::calcArea()
{
    int w = width.getFeet() * 12 + width.getInches();
    int len = length.getFeet() * 12 + length.getInches();
   
    area = (w * len);
}

/* **********************************************************
            Overloaded == operator
    Returns true if the current object is set to a value equal
    to that of right.
   ********************************************************** */

bool LandTract::operator == (const LandTract &right)
{
    bool status;

    if (area == right.area)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

LandTractDm.cpp


#include "LandTract.h"

#include <iomanip>
using std::setprecision;

#include <iostream>
using std::fixed;
using std::cin;
using std::cout;

int main()
{
    const double TO_SQR_FT = 144.0;

    FeetInches w, l;

    cout << "Land Tract Area Calculator\n\n";
    cout << "This program lets you enter the dimensions for two tracts of land.\n"
          << "It will calculate the area for each, and output the result in square feet.\n"
          << "In addition it will tell you, whether the tracts are of same size.\n\n";

    cout << "Enter the width of tract #1:\n\n";
    cin >> w;
    cout << "\nEnter the length of tract #1:\n\n";
    cin >> l;

    LandTract lot(w, l);

    cout << "\nThe area of your lot is: ";
    cout << setprecision(2) << fixed;
    cout << (lot.getArea() / TO_SQR_FT) << " sq. ft.\n\n";

    cout << "Enter the width of tract #2:\n\n";
    cin >> w;
    cout << "\nEnter the length of tract #2:\n\n";
    cin >> l;

    LandTract garden(w, l);

    cout << "\nThe area of your garden is: ";
    cout << (garden.getArea() / TO_SQR_FT) << " sq. ft.\n\n";

    if (lot == garden)
    {
        cout << "Both tracts of land are of equal size.";
    }
    else
    {
        cout << "The tracts of land are of different size.";
    }

    cin.get();
    cin.ignore();
    return 0;
}

Example Output:





Tuesday, January 2, 2018

Happy New Year - An Outlook



Dear visitors, fellow students, and those who happen to visit this person's humble blog for the first time: I wish all of you a Happy New Year! May it be a successful one!

On this occasion let me tell you a little about the goals for this year. On top of the list is finishing Starting Out with C++ 9/E. With 4 Programming Challenges to be solved and 7 chapters to go, the goal is to get done with it until summer.

The next goal is to (finally) dive into the wonderful world of (2D) game programming. For this task, the following books will be used, which I received as christmas presents:

Beginning C++ Game Programming - by John Horton.
SFML Game Development by Example - by Raimondas Pupius
Procedural Content Generation for C++ - by Dale Green
SFML Blueprints - by Maxime Barbier

Hopefully, if all goes as planned, the first game will follow. However humble it will turn out to be, I hope that it will bring a little joy into the lifes of many people, something that entertains children and adults alike.

Besides programming, there are hundreds of hours of music waiting to listen to (this is an easy goal, as I always listen to good music to keep the good spirits up, currently it is mainly Yo-Yo Ma), about 56 books to be read, (the first book being "The Brothers Karamazov"), and getting back into 3D-design, starting and finishing a scene every month, (or in less time than that). This should be enough for this year to keep this person busy. 

And with this, it is back to the IDE, to solve the remaining Programming Challenges of this chapter. I wish my visitors and fellow students that you be able to achieve all goals you have set for yourself this year, and that you will come by from time to time, to see whatever little progress this person has made in an attempt to move past the beginning stages of programming in C++.

Programming Challenge 14.11 - FeetInches Class Copy Constructor and Multiply Function

Example Files: FeetInchesCcMult.7z

FeetInches.h


#ifndef FEET_INCHES_H_
#define FEET_INCHES_H_

#include <iostream>
using std::istream;
using std::ostream;

class FeetInches
{
    private:
        int feet;                        // To hold a number of feet
        int inches;                        // To hold a number of inches

        void simplify();                // Defined in FeetInches.cpp

    public:
        FeetInches(int f = 0, int i = 0)
        {
            feet = f;
            inches = i;
            simplify();
        }

        // Copy Constructor
        FeetInches(const FeetInches &obj)
        {
            feet = obj.feet;
            inches = obj.inches;
        }

        // Mutator functions
        void setFeet(int f)
        {
            feet = f;
        }

        void setInches(int i)
        {
            inches = i;
             simplify();
        }

        FeetInches multiply(const FeetInches &);

        // Accessor functions
        int getFeet() const
        { return feet; }

        int getInches() const
        { return inches; }

        // Overload operator functions
        FeetInches operator + (const FeetInches &);            // Overloaded +
        FeetInches operator - (const FeetInches &);            // Overloaded -
        FeetInches operator ++ ();                                    // Prefix ++
        FeetInches operator ++ (int);                                // Postfix ++
   
        bool operator > (const FeetInches &);                    // Overloaded >
        bool operator < (const FeetInches &);                    // Overloaded <
        bool operator == (const FeetInches &);                    // Overloaded ==
        bool operator >= (const FeetInches &);                    // Greater Equal
        bool operator <= (const FeetInches &);                    // Lesser Equal
        bool operator != (const FeetInches &);                    // Inequal

        // Friends
        friend ostream &operator << (ostream &, const FeetInches &);
        friend istream &operator >> (istream &, FeetInches &);
};

#endif

FeetInches.cpp


#include "FeetInches.h"

#include <cstdlib>

#include <iostream>
using std::cout;

/* **********************************************************
            FeetInches::simplify()
    This function checks for values in the inches member
    greater than twelve or less than zero. If such a value is
    found, the numbers in feet and inches are adjusted to
    conform to a standard feet & inches expression. For
    example:

    3 feet 14 inches would be adjusted to 4 feet 2 inches and
    5 feet -2 inches would be adjusted to 4 feet 10 inches.

    The standard library function abs() is used to get the
    absolute value of the inches member. The abs() function
    requires to #include <cstdlib>.
   ********************************************************** */

void FeetInches::simplify()
{
    if (inches >= 12)
    {
        feet += (inches / 12);
        inches = inches % 12;
    }
    else if (inches < 0)
    {
        feet -= ((abs(inches) / 12) + 1);
        inches = 12 - (abs(inches) % 12);
    }
}

/* **********************************************************
            Overloaded binary + operator
   ********************************************************** */

FeetInches FeetInches::operator + (const FeetInches &right)
{
    FeetInches temp;

    temp.inches = inches + right.inches;
    temp.feet = feet + right.feet;
    temp.simplify();

    return temp;
}

/* **********************************************************
            Overloaded binary - operator
   ********************************************************** */

FeetInches FeetInches::operator - (const FeetInches &right)
{
    FeetInches temp;

    temp.inches = inches - right.inches;
    temp.feet = feet - right.feet;
    temp.simplify();

    return temp;
}

/* **********************************************************
            Overloaded prefix ++ operator
    Causes the inches member to be incremented. Returns the
    incremented object.
   ********************************************************** */

FeetInches FeetInches::operator++()
{
    ++inches;
    simplify();

    return *this;
}

/* **********************************************************
            Overloaded postfix ++ operator
    Causes the inches member to be incremented. Returns the
    value of the object before the increment.
   ********************************************************** */

FeetInches FeetInches::operator++(int)
{
    FeetInches temp(feet, inches);

    inches++;
    simplify();

    return temp;
}

/* **********************************************************
            Overloaded > operator
    Returns true if the current object is set to a value
    greater than that of right.
   ********************************************************** */

bool FeetInches::operator > (const FeetInches &right)
{
    bool status;

    if (feet > right.feet)
    {
        status = true;
    }
    else if (feet == right.feet && inches > right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded < operator
    Returns true if the current object is set to a value less
    than that of right.
   ********************************************************** */

bool FeetInches::operator < (const FeetInches &right)
{
    bool status;

    if (feet < right.feet)
    {
        status = true;
    }
    else if (feet == right.feet && inches < right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded == operator
    Returns true if the current object is set to a value equal
    to that of right.
   ********************************************************** */

bool FeetInches::operator == (const FeetInches &right)
{
    bool status;

    if (feet == right.feet && inches == right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded Greater Equal => operator
    Returns true if the current object is set to a value
    greater than or equal to that of right.
   ********************************************************** */

bool FeetInches::operator >= (const FeetInches &right)
{
    bool status;

    if (feet >= right.feet)
    {
        return true;
    }
    else if (feet == right.feet && inches >= right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded Less Equal <= operator
    Returns true if the current object is set to a value less
    than or equal to that of right.
   ********************************************************** */

bool FeetInches::operator <= (const FeetInches &right)
{
    bool status;

    if (feet <= right.feet)
    {
        status = true;
    }
    else if (feet == right.feet && inches <= right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded Inequal != operator
    Returns true if the current object is set to a value not
    equal to that of right.
    ********************************************************** */

bool FeetInches::operator != (const FeetInches &right)
{
    bool status;

    if (feet != right.feet)
    {
        status = true;
    }
    else if (feet == right.feet && inches != right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            FeetInches::FeetInches multiply() : const obj &
    This function multiplies two FeetInches objects. The feet
    and inches attributes are multiplied by the calling feet
    and inches object's feet and inches attributes, and a
    FeetInches object holding the result is returned.
    ********************************************************** */

FeetInches FeetInches::multiply(const FeetInches &right)
{
    FeetInches temp;

    temp.inches = ((feet * 12 + inches) * (right.feet * 12 + right.inches));
    temp.inches /= 12;
    temp.simplify();

    return temp;
}

/* **********************************************************
            Overloaded << operator
    Gives cout the ability to directly display FeetInches
    objects.
   ********************************************************** */

ostream &operator << (ostream &strm, const FeetInches &obj)
{
    strm << obj.feet << " feet, " << obj.inches << " inches.";

    return strm;
}

/* **********************************************************
            Overloaded >> operator
    Gives cin the ability to directly store user input into
    FeetInches objects.
   ********************************************************** */

istream &operator >> (istream &strm, FeetInches &obj)
{
    // Prompt the user for the feet
    cout << "Feet: ";
    strm >> obj.feet;

    // Prompt the user for the inches
    cout << "Inches: ";
    strm >> obj.inches;

    // Normalize the values
    obj.simplify();

    return strm;
}

FeetInchesDm.cpp


#include "FeetInches.h"

#include <iostream>
using std::cin;
using std::cout;

int main()
{
    FeetInches first(15, 4);
    FeetInches second = first;   
    FeetInches third, fourth;

    cout << "FEET INCHES - COPY CONSTRUCTOR & MULTIPLICATION DEMO\n\n"
          << "This program asks you to input two distances, measured in feet and inches.\n"
          << "It will multiply both values, and output the result in feet and inches.\n";
    cout << "Here is an example:\n\n";

    cout << first << " multiplied by " << second << " equals:\n";
    cout << first.multiply(second) << " \n\n";

    cout << "Enter a distance in feet and inches:\n";
    cin >> third;
   
    cout << "\nEnter another distance in feet and inches.\n";
    cin >> fourth;
   
    cout << "\n" << third << " multiplied by " << fourth << " equals:\n";
    cout << (third.multiply(fourth));

    cout << "\n\nThank you for using this demo. Have a nice day!";

    cin.get();
    cin.ignore();
    return 0;
}

Example Output: 



Thursday, December 28, 2017

Programming Challenge 14.10 - Corporate Sales

Example Files: CorporateSales.7z

DivSales.h


#ifndef DIVISION_SALES_H
#define DIVISION_SALES_H

#include <array>
using std::array;

const int NUM_DIVS = 6;
const int NUM_QTRS = 4;

class DivSales
{
    private:
        array <double, NUM_QTRS> divSales;            // Holds the sales figures for 4 quarters
        static double totalCorpSales;                    // Holds the total sales of all divisions

    public:
        DivSales();

        void addSales(array <double, NUM_QTRS> &);

        double getQuarterlySales(int qtr) const
        {
            return divSales[qtr];
        }

        double getTotalCorpSales() const
        {
            return totalCorpSales;
        }
};

#endif

DivSales.cpp


#include "DivSales.h"

double DivSales::totalCorpSales = 0;

/* **********************************************************
            DivSales::DivSales() : Default Constructor
   ********************************************************** */

DivSales::DivSales()
{
    for (size_t idx = 0; idx < NUM_QTRS; idx++)
    {
        divSales[idx] = 0;
    }
}

/* **********************************************************
            DivSales::addSales() : array &
    This function is passed an array holding four quarterly
    sales figures. The values are copied into the salesFigures
    array, and the static member variable totalCorpSales adds
    to it the total sum of these values.
   ********************************************************** */

void DivSales::addSales(array <double, NUM_QTRS> &qtrSales)
{
    for (size_t i = 0; i < NUM_QTRS; i++)
    {
        totalCorpSales += divSales[i] = qtrSales[i];
    }   
}

DivSalesDm.cpp


#include "DivSales.h"

#include <array>
using std::array;

#include <iomanip>
using std::setprecision;

#include <iostream>
using std::cin;
using std::cout;
using std::fixed;

void getSales(array <DivSales, NUM_DIVS> &);
void outputSales(const array <DivSales, NUM_DIVS> &);

int main()
{
    array <DivSales, NUM_DIVS> divSales;

    cout << "ISHIKAWA FRUIT COMPANY - CORPORATE SALES DATA 2017\n\n";

    getSales(divSales);
    outputSales(divSales);

    cout << "\nISHIKAWA FRUIT COMPANY - Your number one fruit supplier!\n";

    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
            getSales() : array &
    This function accepts an array of six DivSales objects as
    its argument. It asks the user to input four quarterly
    sales results.
   ********************************************************** */

void getSales(array<DivSales, NUM_DIVS> &salesQtr)
{
    array <double, NUM_QTRS> sales;

    for (int div = 0; div < NUM_DIVS; div++)
    {
        cout << "Enter sales for Division " << (div + 1) << "\n";

        for (int idx = 0; idx < NUM_QTRS; idx++)
        {
            cout << "Quarter " << (idx + 1) << ": JPY ";
            cin >> sales[idx];

            while (sales[idx] <= 0)
            {
                cout << "Quarter " << (idx + 1) << ": JPY ";
                cin >> sales[idx];
            }
        }

        salesQtr[div].addSales(sales);
        cout << "\n";
    }
}

/* **********************************************************
            getSales() : const array &
    This function accepts an array of six DivSales objects,
    holding four quarterly sales for each of its devisions, as
    its argument. The quarterly sales for each division, and
    the total sales of all divisions is output to screen.
   ********************************************************** */

void outputSales(const array <DivSales, NUM_DIVS> &salesQtr)
{
    DivSales corpTotal;
   
    cout << "\nISHIKAWA FRUIT COMPANY - SALES RESULTS 2017\n\n";
    cout << fixed << setprecision(2);

    for (int div = 0; div < NUM_DIVS; div++)
    {
        cout << "Division " << (div + 1) << "\n";
        for (int idx = 0; idx < NUM_QTRS; idx++)
        {
            cout << "Quarter " << (idx + 1) << ": JPY ";
            cout << salesQtr[div].getQuarterlySales(idx) << "\n";
        }
        cout << "\n";
    }

    cout << "Total Sales: JPY " << corpTotal.getTotalCorpSales() << "\n";
}

Example Output:

 


Wednesday, December 27, 2017

Programming Challenge 14.9 - Feet Inches Modification

Example Files: FeetInchesModification.7z

This code is based on the FeetInches.h and FeetInches.cpp version 4, found on pp. 856 through 858. The modification consists of three additional overloads written for this modification, and, for consitency, kept in the same style as is found in the other functions provided by the book. The driver is demonstrating only the new functionality introduced by this modification.

FeetInches.h


#ifndef FEET_INCHES_H_
#define FEET_INCHES_H_

#include <iostream>
using std::istream;
using std::ostream;

class FeetInches
{
    private:
        int feet;                        // To hold a number of feet
        int inches;                        // To hold a number of inches

        void simplify();                // Defined in FeetInches.cpp

    public:

        FeetInches(int f = 0, int i = 0)
        {
            feet = f;
            inches = i;
            simplify();
        }

        // Mutator functions
        void setFeet(int f)
        { feet = f; }

        void setInches(int i)
        {
            inches = i;
            simplify();
        }

        // Accessor functions
        int getFeet() const
        { return feet; }

        int getInches() const
        { return inches; }

        // Overload operator functions
        FeetInches operator + (const FeetInches &);            // Overloaded +
        FeetInches operator - (const FeetInches &);            // Overloaded -
        FeetInches operator ++ ();                                    // Prefix ++
        FeetInches operator ++ (int);                                // Postfix ++

        bool operator > (const FeetInches &);                    // Overloaded >
        bool operator < (const FeetInches &);                    // Overloaded <
        bool operator == (const FeetInches &);                    // Overloaded ==
        bool operator >= (const FeetInches &);                    // Greater Equal
        bool operator <= (const FeetInches &);                    // Lesser Equal
        bool operator != (const FeetInches &);                    // Inequal

        // Friends
        friend ostream &operator << (ostream &, const FeetInches &);
        friend istream &operator >> (istream &, FeetInches &);
};

#endif

FeetInches.cpp


#include "FeetInches.h"

#include <cstdlib>

#include <iostream>
using std::cin;
using std::cout;

/* **********************************************************
            FeetInches::simplify()
    This function checks for values in the inches member
    greater than twelve or less than zero. If such a value is
    found, the numbers in feet and inches are adjusted to
    conform to a standard feet & inches expression. For
    example:

    3 feet 14 inches would be adjusted to 4 feet 2 inches and
    5 feet -2 inches would be adjusted to 4 feet 10 inches.

    The standard library function abs() is used to get the
    absolute value of the inches member. The abs() function
    requires to #include <cstdlib>.
   ********************************************************** */

void FeetInches::simplify()
{
    if (inches >= 12)
    {
        feet += (inches / 12);
        inches = inches % 12;
    }
    else if (inches < 0)
    {
        feet -= ((abs(inches) / 12) + 1);
        inches = 12 - (abs(inches) % 12);
    }
}

/* **********************************************************
            Overloaded binary + operator
   ********************************************************** */

FeetInches FeetInches::operator + (const FeetInches &right)
{
    FeetInches temp;

    temp.inches = inches + right.inches;
    temp.feet = feet + right.feet;
    temp.simplify();

    return temp;
}

/* **********************************************************
            Overloaded binary - operator
   ********************************************************** */

FeetInches FeetInches::operator - (const FeetInches &right)
{
    FeetInches temp;

    temp.inches = inches - right.inches;
    temp.feet = feet - right.feet;
    temp.simplify();

    return temp;
}

/* **********************************************************
            Overloaded prefix ++ operator
    Causes the inches member to be incremented. Returns the
    incremented object.
   ********************************************************** */

FeetInches FeetInches::operator++()
{
    ++inches;
    simplify();

    return *this;
}

/* **********************************************************
            Overloaded postfix ++ operator
    Causes the inches member to be incremented. Returns the
    value of the object before the increment.
   ********************************************************** */

FeetInches FeetInches::operator++(int)
{
    FeetInches temp(feet, inches);

    inches++;
    simplify();

    return temp;
}

/* **********************************************************
            Overloaded > operator
    Returns true if the current object is set to a value
    greater than that of right.
   ********************************************************** */

bool FeetInches::operator > (const FeetInches &right)
{
    bool status;

    if (feet > right.feet)
    {
        status = true;
    }
    else if (feet == right.feet && inches > right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded < operator
    Returns true if the current object is set to a value less
    than that of right.
   ********************************************************** */

bool FeetInches::operator < (const FeetInches &right)
{
    bool status;

    if (feet < right.feet)
    {
        status = true;
    }
    else if (feet == right.feet && inches < right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded == operator
    Returns true if the current object is set to a value equal
    to that of right.
   ********************************************************** */

bool FeetInches::operator == (const FeetInches &right)
{
    bool status;

    if (feet == right.feet && inches == right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded Greater Equal => operator
    Returns true if the current object is set to a value
    greater than or equal to that of right.
   ********************************************************** */

bool FeetInches::operator >= (const FeetInches &right)
{
    bool status;

    if (feet >= right.feet)
    {
        return true;
    }
    else if (feet == right.feet && inches >= right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded Less Equal <= operator
    Returns true if the current object is set to a value less
    than or equal to that of right.
   ********************************************************** */

bool FeetInches::operator <= (const FeetInches &right)
{
    bool status;

    if (feet <= right.feet)
    {
        status = true;
    }
    else if (feet == right.feet && inches <= right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded Inequal != operator
    Returns true if the current object is set to a value not
    equal to that of right.
    ********************************************************** */

bool FeetInches::operator != (const FeetInches &right)
{
    bool status;

    if (feet != right.feet)
    {
        status = true;
    }
    else if (feet == right.feet && inches != right.inches)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

/* **********************************************************
            Overloaded << operator
    Gives cout the ability to directly display FeetInches
    objects.
   ********************************************************** */

ostream &operator << (ostream &strm, const FeetInches &obj)
{
    strm << obj.feet << " feet, " << obj.inches << " inches";

    return strm;
}

/* **********************************************************
            Overloaded >> operator
    Gives cin the ability to directly store user input into
    FeetInches objects.
   ********************************************************** */

istream &operator >> (istream &strm, FeetInches &obj)
{
    // Prompt the user for the feet
    cout << "Feet: ";
    strm >> obj.feet;

    // Prompt the user for the inches
    cout << "Inches: ";
    strm >> obj.inches;

    // Normalize the values
    obj.simplify();

    return strm;
}

FeetInchesModificationDm.cpp


#include "FeetInches.h"

#include <iostream>
using std::cin;
using std::cout;

int main()
{
    FeetInches first, second;

    cout << "FEET INCHES MODIFICATION\n\n"
          << "This program asks you to enter two lenghts, measured in feet and inches.\n"
          << "It then tells you whether one distance is:\n\n"
          << "\tGreater than or equal to the other\n"
          << "\tLess than or equal to the other\n"
          << "\tNot the same as the other.\n\n";

    for (int i = 0; i < 3; i++)
    {
        cout << "Enter a distance in feet and inches.\n";
        cin >> first;

        cout << "Enter another distance in feet and inches.\n";
        cin >> second;

        cout << "\nThe values you entered are:\n";
        cout << first << " and " << second << "\n\n";

        if (first >= second)
        {
            cout << "True: First is greater than or equal to second.\n";
        }
        else
        {
            cout << "False: First is not greater than or equal to second.\n";
        }

        if (first <= second)
        {
            cout << "True: First is less than or equal to second.\n";
        }
        else
        {
            cout << "False: First is not less than or equal to second.\n";
        }

        if (first != second)
        {
            cout << "True: First does not equal second.\n";
        }
        else
        {
            cout << "False: First equals second.\n";
        }
        cout << "\n";
    }

    cout << "\nThank you for using this demo. Have a nice day!";

    cin.get();
    cin.ignore();
    return 0;
}

Example Output:




Monday, December 25, 2017

Programming Challenge 14.8 - Date Class Modification

Example Files: DateClassModification.7z

Date.h


/* Date.h - Specification file for the Date class. */

#ifndef DATE_H
#define DATE_H

#include <array>
using std::array;

#include <iostream>
using std::istream;
using std::ostream;

#include <string>
using std::string;

class Date
{
    private:       
        static const array<int, 13> daysPerMonth;            // Holds number of days per month
        static const array<string, 13> monthNames;        // Holds month names (JAN -> DEC)

        int month;                        // Holding the month
        int day;                            // Holding the day 
        int year;                        // Holding the year
        int difference;                // Holding the difference in days between two dates

    public:
        Date() { }
        Date(int, int, int);            // Constructor accepting arguments
        ~Date() {}                        // Destructor

        void setYear(int);
        void setMonth(int);
        void setDay(int);
        bool isLeapYear() const;
        void helpIncrement();
        void helpDecrement();
        int calcJulianDate(const Date &);
        void printFormatOne();
        void printFormatTwo();
        void printFormatThree();

        int getYear() const
        { return year; }

        int getMonth() const
        { return month; }

        int getDay() const
        { return day; }

        int getDifference() const
        { return difference; }

        // Overloaded operator functions
        Date &operator ++();                        // Prefix ++
        Date operator ++(int);                    // Postfix ++
        Date &operator --();                        // Prefix --
        Date operator --(int);                    // Postfix --
        Date operator -(const Date &);        // Binary -
        bool operator >(const Date &);        // Greater 

        // Friends
        friend istream &operator >> (istream &, Date &);
        friend ostream &operator << (ostream &, const Date &);       
};
#endif

Date.cpp


/* Date.cpp - Implementation file for the Date class. */

#include "Date.h"

#include <array>
using std::array;

#include <iostream>
using std::cout;

#include <string>
using std::string;

// Initializes the daysPerMonth array with the days per month
const array<int, 13> Date::daysPerMonth{ 0, 31, 28, 31, 30, 31, 30,
                                                            31, 31, 30, 31, 30, 31 };

// Initializes the monthNames array with the names of the months of the year
const array<std::string, 13> Date::monthNames{ "", "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
                                                                    "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };

enum Months { JANUARY = 1, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER };

/* **********************************************************
            Date::Date() : int, int, int
    The constructor accepts arguments for year, month and day.
    ********************************************************** */

Date::Date(int yyyy, int mm, int dd)
{
    setYear(yyyy);
    setMonth(mm);
    setDay(dd);
}

/* **********************************************************
            Date::setYear() : int
    If the argument passed to the setYear function is greater
    than or equal to 1900 and less than or equal to 2020, it
    is copied into the 'year' member. If it is not, the value
    of year is set to 1900.
    ********************************************************** */

void Date::setYear(int yyyy)
{
    yyyy >= 1900 && yyyy <= 2020 ? year = yyyy : year = 1900;
}

/* **********************************************************
            Date::setMonth() : int
    If the argument passed to the setMonth function is greater
    than or equal to JANUARY and lower than or equal to
    DECEMBER, it is copied into the member variable month. If
    it is not, the month value is set to 1.
    ********************************************************** */

void Date::setMonth(int mm)
{
    mm >= JANUARY && mm <= DECEMBER ? month = mm : month = 1;
}

/* **********************************************************
            Date::setDay() : int
    If the argument passed to the setDay function is greater
    than 1 and less than or equal to daysPerMonth (ex: April
    has 30 days), it is assigned to the day member variable.
    If it is a leap year, days is set to 29, else 28 is set.
    If neither of these conditions are met, day is set to 1.
    Else, if the value dd is in the valid range, its value is
    assigned ot the day member variable.
    ********************************************************** */

void Date::setDay(int dd)
{
    if (month == FEBRUARY && isLeapYear() && dd == 29)
    {
        day = 29;
    }
    else if (month == FEBRUARY && dd > daysPerMonth[getMonth()])
    {
        day = 28;
    }
   
    else if (dd < 1 || dd > daysPerMonth[getMonth()])
    {
        day = 1;
    }
    else
    {
        day = dd;
    }
}

/* **********************************************************
            Date::isLeapYear()
    This function determines whether a year is a leap year. If
    it is true is returned, else it returns false.
    ********************************************************** */

bool Date::isLeapYear() const
{
    if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
    {
        return true;
    }
    return false;
}

/* **********************************************************
            Date::helpIncrement()
    This helper function determines whether the day, day and
    month, or day month and year values should be incremented.
    ********************************************************** */

void Date::helpIncrement()
{
    if (day > daysPerMonth[month] && month < DECEMBER)
    {   
        if (day >= 30)
        {
            month++;
            day = 1;   
        }
        else if (month == FEBRUARY && isLeapYear())
        {
            day = 29;           
        }
        else if (month == FEBRUARY && !isLeapYear())
        {
            month++;
            day = 1;       
        }           
    }       
   
    if (month == DECEMBER && day > 31)
    {
        year++;
        month = 1;
        day = 1;
    }
}

/* **********************************************************
            Date &Date::operator++() : Prefix ++
   ********************************************************** */

Date &Date::operator++()
{
    ++day;
    helpIncrement();
    return *this;
}

/* **********************************************************
            Date Date::operator++(int) : Postfix ++
   ********************************************************** */

Date Date::operator++(int)
{
    Date tempDate(year, month, day);

    day++;
    helpIncrement();

    return tempDate;
}

/* **********************************************************
            Date::helpDecrement()
    This helper function determines whether year or month
    should be decremented. If a condition is met, the day and
    month member variables are set accordingly.
    ********************************************************** */

void Date::helpDecrement()
{
    if (month == JANUARY)
    {
        month = DECEMBER;
        day = 31;
        year--;
    }   
    else
    {
        month--;

        if (daysPerMonth[month] == 31)
        {
            day = 31;
        }
        else if (daysPerMonth[month] == 30)
        {
            day = 30;
        }
        else if (month == FEBRUARY && isLeapYear())
        {
            day = 29;
        }
        else
        {
            day = 28;
        }
    }
}

/* **********************************************************
            Date Date::operator--() : Prefix --
   ********************************************************** */

Date &Date::operator--()
{
    if (day > 1)
    {
        --day;
    }
    else
    {
        helpDecrement();
    }

    return *this;
}

/* **********************************************************
            Date Date::operator--(int) : Postfix --
   ********************************************************** */

Date Date::operator--(int)
{
    Date tempDate(year, month, day);

    if (day > 1)
    {
        day--;
    }
    else
    {
        helpDecrement();
    }

    return tempDate;
}

/* **********************************************************
            Date::calcJulianDate() : const Date &
    This function calculates the Julian dates for two date
    objects. (The formula used for calculation can be found in
    the Wiki-Article: Julian day)
    ********************************************************** */

int Date::calcJulianDate(const Date &dateOne)
{
    int julianDate = (1461 * (dateOne.year + 4800 + (dateOne.month - 14) / 12)) / 4 +
                          (367 * (dateOne.month - 2 - 12 * ((dateOne.month - 14) / 12))) / 12 -
                          (3 * ((dateOne.year + 4900 + (dateOne.month - 14) / 12) / 100)) / 4 +
                          (dateOne.day - 32075);

    return julianDate;
}

/* **********************************************************
            bool Date::operator >() : Greater
    ********************************************************** */

bool Date::operator >(const Date &right)
{
    if (year > right.year)
    {
        return true;
    }

    if (year == right.year && month > right.month)
    {
        return true;
    }

    if (year == right.year && month == right.month && day > right.day)
    {
        return true;
    }

    return false;
}

/* **********************************************************
            Date Date::operator -() : Binary -
    ********************************************************** */

Date Date::operator-(const Date &right)
{
    Date temp;
    Date tempOne = right;

    temp.year = year;
    temp.month = month;
    temp.day = day;

    temp.difference = calcJulianDate(temp);
    tempOne.difference = calcJulianDate(tempOne);

    if (temp > tempOne)
    {
        temp.difference = (temp.difference - tempOne.difference);
    }
    else if (tempOne > temp)
    {
        temp.difference = (tempOne.difference - temp.difference);
    }

    return temp;
}

/* **********************************************************
            Date Date::operator >> () : Extraction operator
   ********************************************************** */

istream &operator >> (istream &strm, Date &obj)
{
    cout << "Enter a year: (1900 - 2020): ";
    strm >> obj.year;
    obj.setYear(obj.year);

    cout << "Enter a month (1 - 12): ";
    strm >> obj.month;
    obj.setMonth(obj.month);

    cout << "Enter a day: ";
    strm >> obj.day;
    obj.setDay(obj.day);

    return strm;
}

/* **********************************************************
            Date Date::operator << () : Insertion operator
   ********************************************************** */

ostream &operator << (ostream &strm, const Date &obj)
{
    return strm << obj.monthNames[obj.month] << " " << obj.day << ", " << obj.year;
}

/* **********************************************************
            Date::printFormatOne()
    This function outputs the date as 12/12/2012.
    ********************************************************** */

void Date::printFormatOne()
{
    cout << "\nSlash Style:\n";
    cout << month << "/" << day << "/" << year;
}

/* **********************************************************
            Date::printFormatTwo (void)
    This function outputs the date as DECEMBER 12, 2012
    ********************************************************** */

void Date::printFormatTwo()
{
    std::cout << "\n\nU.S. Style:\n";
    std::cout << monthNames[month] << " " << day << ", " << year;
}

/* **********************************************************
            Date::printFormatThree (void)
    This function outputs the date as 12 DECEMBER, 2012
    ********************************************************** */

void Date::printFormatThree()
{
    cout << "\n\nEuropean Style:\n";
    cout << day << " " << monthNames[month] << " " << year;
}

DateDemo.cpp


/* Date Demo - This is a modified version of the Date class, written for Programming
                    Challenge 13.1. */

#include "Date.h"

#include <iostream>
using std::cin;
using std::cout;

int main()
{
    cout << "MODIFIED DATE CLASS DEMO\n\n"
          << "This program demonstrates various abilities of the modified\n"
          << "Date class, written for Programming Challenge 13.1.\n\n";

    cout << "Demonstrating the output of a date in three different styles:\n";
    Date date(2009, 6, 7);
    date.printFormatOne();
    date.printFormatTwo();
    date.printFormatThree();

    cout << "\n\nDemonstrating the overloaded Prefix ++ operator:\n";
    Date dateOne(2018, 12, 27);
    cout << "The date is:     " << dateOne << "\n";
    ++dateOne;
    cout << "The new date is: " << dateOne << "\n\n";

    cout << "Demonstrating the overloaded Postfix ++ operator:\n";
    Date dateTwo(2017, 11, 26);
    cout << "The date is:     " << dateTwo << "\n";
    dateTwo++;
    cout << "The new date is: " << dateTwo << "\n\n";

    cout << "Demonstrating the overloaded Prefix -- operator:\n";
    Date dateThree(2012, 1, 1);
    cout << "The date is:     " << dateThree << "\n";
    --dateThree;
    cout << "The new date is: " << dateThree << "\n\n";

    cout << "Demonstrating the overloaded Postfix -- operator:\n";
    Date dateFour(2012, 3, 1);
    cout << "The date is:     " << dateFour << "\n";
    dateFour--;
    cout << "The new date is: " << dateFour << "\n\n";

    cout << "Demonstrating the overloaded Extraction operator:\n\n";
    Date dateFive;
    cin >> dateFive;
    cout << "\nThis is the date you entered: " << dateFive << "\n\n";

    cout << "Demonstrating the overloaded Binary - operator:\n\n";
    cout << "The difference in days between \n"
          << dateFive << " and " << dateTwo << " is: ";
    dateFive = dateFive - dateTwo;
    cout << dateFive.getDifference() << " days.\n\n";

    cout << "Thank you for trying the Date class demo. Have a nice day!";

    cin.ignore();
    cin.get();
   return 0;
}

Example Output: