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:



Tuesday, December 19, 2017

Programming Challenge 14.7 - Month Class

Example Files: MonthClass.7z


Month.h


#ifndef MONTH_H_
#define MONTH_H_

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

#include <string>
using std::string;

const int NUM_MONTHS = 13;

class Month
{
    private:
        static const string monthNames[NUM_MONTHS];        // Array holding month names

        string name;                        // To hold a month name
        int    monthNumber;                // To hold a month number (1 through 12)

    public:
        Month();
        Month(string);
        Month(int);

        void setMonthNumber(const int &);
        void setMonthName(const string &);

        string getMonthName() const
        { return name; }

        int getMonthNumber() const
        { return monthNumber; }

        // Overloaded operator functions
        Month operator++();                    // Prefix ++
        Month operator++(int);                // Postfix ++
        Month operator--();                    // Prefix --
        Month operator--(int);                // Postfix --

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

#endif

Month.cpp


#include "Month.h"

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

// Definition of const static array member holding month names
const string Month::monthNames[] = { "", "January", "February", "March", "April",
                                                 "May", "June", "July", "August", "September",
                                                 "October", "November", "December" };

/* **********************************************************
            Month::Month() - Default Constructor
   ********************************************************** */

Month::Month()
{
    name = "January";
    monthNumber = 1;
}

/* **********************************************************
            Month::Month() : string - Constructor  
    The constructor accepts the name of a month as argument.
    It sets the month name and number via the setMonthName()
    function to the correct value.
   ********************************************************** */

Month::Month(string n)
{
    setMonthName(n);
}

/* **********************************************************
            Month::Month() : int - Constructor
    The constructor accepts the number of a month as argument.
    It sets the month number and name via the setMonthNumber()
    function to the correct value.
   ********************************************************** */

Month::Month(int mNum)
{
    setMonthNumber(mNum);
}

/* **********************************************************
            MonthName::setMonthNumber() : const int &
    This function accepts a const reference to an integer as
    argument. If the value passed to this function is within
    the accepted range, the monthNumber and name each receive
    the correct name and month number. Else, monthNumber and
    name are set to 1 and January.
   ********************************************************** */

void Month::setMonthNumber(const int &mNum)
{
    if (mNum >= 1 && mNum <= 12)
    {
        monthNumber = mNum;
        name = monthNames[mNum];
    }
    else
    {
        monthNumber = 1;
        name = monthNames[monthNumber];
    }
}

/* **********************************************************
            Month::setMonthName() : const string &
    This function accepts a const reference parameter to a
    string object as argument. If the name is valid, name is
    set to the value passed to it, and monthNumber is passed
    the array-index at which the name is stored at. Else, name
    is set to January and monthNumber is set to 1.
   ********************************************************** */

void Month::setMonthName(const string &n)
{
    bool isFound = false;

    for (size_t count = 1; count < NUM_MONTHS; count++)
    {
        if (n == monthNames[count])
        {
            name = n;
            monthNumber = count;
            isFound = true;
        }   
    }

    if (isFound == false)
    {
        cout << "\nInput Error: " << n << " does not exist.\n"
             << "Setting month name and number to default values:\n\n";
        monthNumber = 1;
        name = monthNames[monthNumber];
       
    }
}

/* **********************************************************
            Month Month::operator++() : Prefix ++
   ********************************************************** */

Month Month::operator++()
{
    ++monthNumber;

    getMonthNumber() <= 12 ? setMonthNumber(monthNumber) : setMonthNumber(1);

    return *this;
}

/* **********************************************************
            Month Month::operator++() : Postfix ++
   ********************************************************** */

Month Month::operator++(int)
{
    Month temp(monthNumber);

    monthNumber++;
    getMonthNumber() <= 12 ? setMonthNumber(monthNumber) : setMonthNumber(1);

    return temp;
}

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

Month Month::operator--()
{
    --monthNumber;

    getMonthNumber() >= 1 ? setMonthNumber(monthNumber) : setMonthNumber(12);

    return *this;
}

/* **********************************************************
            Month Month::operator--() : Postfix --
   ********************************************************** */

Month Month::operator--(int)
{
    Month temp(monthNumber);

    monthNumber--;
    getMonthNumber() >= 1 ? setMonthNumber(monthNumber) : setMonthNumber(12);

    return temp;
}

/* **********************************************************
            Month Month::operator >> () : Extraction Operator
   ********************************************************** */

istream &operator >> (istream &strm, Month &obj)
{
    strm >> obj.name;
    obj.setMonthName(obj.name);
   
    return strm;
}

/* **********************************************************
            Month Month::operator << () : Insertion Operator
   ********************************************************** */

ostream &operator << (ostream &strm, const Month &obj)
{
    return strm << obj.name << " is month number " << obj.monthNumber << ".";
}

MonthDm.cpp


#include "Month.h"

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

int main()
{
    cout << "Months Class - Demo\n\n"
          << "This program demonstrates various functions of the Month class.\n\n"
          << "\t1.) The three constructors\n"
          << "\t2.) The overloaded pre- and postfix ++ and -- operators\n"
          << "\t3.) The overloaded istream and ostream operators\n\n"
          << "If a name or month number is invalid, their values are set\n"
          << "to: January and 1.\n\n";

    cout << "\tConstructor Demonstration\n\n";

    cout << "Demonstrating the default constructor\n";
    Month one;
    cout << one.getMonthName() << " is month number " << one.getMonthNumber() << "\n\n";

    cout << "Demonstrating the Second Constructor (Accepting a Month Name)\n";
    Month two("February");
    cout << two.getMonthName() << " is month number " << two.getMonthNumber() << "\n\n";

    cout << "Demonstrating the Third Constructor (Accepting a Mont Number)\n";
    Month three(9);
    cout << "Month " << three.getMonthNumber() << " is " << three.getMonthName() << "\n\n";

    cout << "\tOverloaded Post- and Prefix ++ and -- Operator Demonstration\n\n";
    cout << "Prefix ++\n";
    ++one;
    cout << one.getMonthName() << " is month number " << one.getMonthNumber() << "\n";

    cout << "Postfix ++\n";
    one++;
    cout << one.getMonthName() << " is month number " << one.getMonthNumber() << "\n\n";

    cout << "Prefix --\n";
    --two;
    cout << two.getMonthName() << " is month number " << two.getMonthNumber() << "\n";

    cout << "Postfix --\n";
    two--;
    cout << two.getMonthName() << " is month number " << two.getMonthNumber() << "\n\n";

    cout << "Overloaded Istream and Ostream Operator Demonstration\n\n";
    cout << "Enter a month name (January through December): ";
    Month four;
    cin >> four;
    cout << four;

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

Example Output:





Sunday, December 17, 2017

Programming Challenge 14.6 - Personell Report

Example Files: PersonellReport.7z

The following changes have been applied to the TimeOff.h and TimeOff.cpp files:
- A constructor accepting a string object and an integer and a default constructor has been added
- The ternary previously in the constructor has been placed in the setMaxVacation() function. This, function is now also called from the constructor.
- MAX_PAID has been moved to the global space of the classes header file

PersonellReport.h


#ifndef PERSONELL_REPORT_H_
#define PERSONELL_REPORT_H_

#include "TimeOff.h"

const int SICK_DAYS = 8;                // The number of sick days added per month
const int VAC_DAYS = 12;                // The number of paid vacation days added per month

class PersonellReport
{
    private:
        int     monthsEmployed;            // To hold a number of months
        TimeOff daysOff;                    // A TimeOff object
       
    public:
        PersonellReport(const TimeOff &, int);

        void addMaxSickDays(int m)
        {
            daysOff.setMaxSick(m * SICK_DAYS);
        }

        void addMaxVacation(int m)
        {
            daysOff.setMaxVacation(m * VAC_DAYS);
        }

        void print();

        int getMonthsEmployed() const
        { return monthsEmployed; }
};

#endif

PersonellReport.cpp


#include "PersonellReport.h"

#include <iostream>
using std::cout;

/* **********************************************************
       PersonellReport::PersonellReport() : Constructor
   ********************************************************** */

PersonellReport::PersonellReport(const TimeOff &t, int m)
{
    daysOff = t;
    monthsEmployed = m;

    addMaxSickDays(m);
    addMaxVacation(m);
}

/* **********************************************************
            PersonellReport::print()  
    This function outputs an employee's ID, name, months of
    employment, the number of days of sick leave, 8 per month,
    and the number of days of paid vacation, 12 per month, the
    employee is entitled to consume.
   ********************************************************** */

void PersonellReport::print()
{
    cout << "\nEmployee ID:   " << daysOff.getEmployeeID() << "\n";
    cout << "Employee Name:  " << daysOff.getEmployeeName() << "\n";
    cout << "Employed since: " << getMonthsEmployed() << " month(s)\n\n";

    cout << "This employee is granted the following:\n\n";
    cout << "A maximum number of " << daysOff.getMaxSick() << " sick days.\n";
    cout << "A maximum number of " << daysOff.getMaxVacation() << " days of paid vacation.";
}

PersonellReportDm.cpp


#include "PersonellReport.h"
#include "TimeOff.h"

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

int main()
{
    int months = 0;

    TimeOff empOne("Precious Ramotswe", 1);
   
    cout << "No. 1 Ladies' Detective Agency - Personell Report\n\n";
    cout << "Employee ID:   " << empOne.getEmployeeID() << "\n";
    cout << "Employee Name: " << empOne.getEmployeeName() << "\n\n";
       
    cout << "Enter number of months of employement (1 through 360): ";
    cin >> months;

    while (months <= 0 || months > 360)
    {
        cout << "Enter number of months of employement (1 through 360): ";
        cin >> months;
    }

    PersonellReport one(empOne, months);
    one.print();

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

Example Output:



Saturday, December 16, 2017

Programming Challenge 14.5 - Time Off

Example Files: TimeOff.7z

Because the NumDays.h and NumDays.cpp files contents have not changed, they are contained in the .7z file but not displayed separately here.

TimeOff.h


#ifndef TIME_OFF_H_
#define TIME_OFF_H_

#include "NumDays.h"

#include <string>
using std::string;

class TimeOff
{
    private:
        string employeeName;                    // Holding an employee's name
        int    employeeID;                    // Holding an employee's ID

        NumDays maxSickDays, sickTaken,
              maxVacation, vacTaken,
                  maxUnpaid, unpaidTaken;

    public:
        TimeOff(string, int, double, double, double, double, double, double);

        // Mutators
        void setEmployeeName(string name)
        { employeeName = name; }

        void setEmployeeID(int ID)
        { employeeID = ID; }

        void setMaxSick(double hrs)
        { maxSickDays.setHours(hrs); }

        void setSickTaken(double hrs)
        { sickTaken.setHours(hrs); }

        void setMaxVacation(double hrs)
        { maxVacation.setHours(hrs); }

        void setVacTaken(double hrs)
        { vacTaken.setHours(hrs); }

        void setMaxUnpaid(double hrs)
        { maxUnpaid.setHours(hrs); }

        void setUnpaidTaken(double hrs)
        { unpaidTaken.setHours(hrs); }

        void print();

        // Accessors
        string getEmployeeName() const
        { return employeeName; }

        int getEmployeeID() const
        { return employeeID; }

        double getMaxSick() const
        { return maxSickDays.getDays(); }

        double getSickTaken() const
        { return sickTaken.getDays(); }

        double getMaxVacation() const
        { return maxVacation.getDays(); }

        double getVacationTaken() const
        { return vacTaken.getDays(); }

        double getMaxUnpaid() const
        { return maxUnpaid.getDays(); }

        double getUnpaidTaken() const
        { return unpaidTaken.getDays(); }
};

#endif

TimeOff.cpp


#include "TimeOff.h"

#include <iomanip>
using std::setprecision;
using std::setw;

#include <iostream>
using std::cout;
using std::fixed;
using std::left;
using std::right;
using std::showpoint;

// Maximum amount of paid vacation days
const int MAX_PAID = 240;

/* **********************************************************
            TimeOff::TimeOff() - Constructor
   ********************************************************** */

TimeOff::TimeOff(string name, int ID, double maxSick, double sickT,
                                                  double maxVac, double vacT,
                                                  double maxUnp, double unpT)
{
    employeeName = name;
    employeeID = ID;

    setMaxSick(maxSick);
    setSickTaken(sickT);

    maxVac <= MAX_PAID ? setMaxVacation(maxVac) :
                                setMaxVacation(MAX_PAID);

    setVacTaken(vacT);
    setMaxUnpaid(maxUnp);
    setUnpaidTaken(unpT);
}

/* **********************************************************
            TimeOff::print()
    This function outputs a summary about an employee's days
    off.
   ********************************************************** */

void TimeOff::print()
{
    cout << fixed << showpoint << setprecision(2);

    cout << setw(15) << left << "Employee ID: " << getEmployeeID() << "\n"
          << setw(15) << right << "Employee Name: " << setw(5) << right << getEmployeeName() << "\n\n";
   
    cout << left << "Max. Sick Days: " << setw(6) << left << getMaxSick() << "\n"
          << setw(16) << right << "Sick Days: " << setw(5) << right << getSickTaken() << "\n\n";
    cout << left << "Max. Vacation Days: " << setw(7) << left << getMaxVacation() << "\n"
          << setw(20) << "Vacation Days: " << setw(4) << right << getVacationTaken() << "\n\n";
    cout << left << "Max. Unpaid Days: " << setw(6) << left << getMaxUnpaid() << "\n"
          << setw(18) << right << "Unpaid Days: " << setw(4) << right << getUnpaidTaken() << "\n\n\n";
}

TimeOffDm.cpp


 #include "TimeOff.h"

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

int main()
{
    // Array of 2 TimeOff objects, initialized with the following data:
    // Employee name, ID, Max. sick days, sick days taken, Max. vacation,
    // vacation taken, Max. unpaid vacation days, unpaid vacation days taken
    TimeOff offDays[2] = { TimeOff("Precious Ramotswe", 1, 200, 30, 255, 86, 40, 10),
                                  TimeOff("Grace Makutsi", 2, 164, 10, 20, 50, 40, 10) };

    cout << "No. 1 Ladies' Detective Agency - Leave Tracker\n\n";
    for (auto outputDays : offDays)
    {
        outputDays.print();
    }
  
    cin.get();
    cin.ignore();
    return 0;
}

Example Output:




Thursday, December 14, 2017

Programming Challenge 14.4 - NumDays Class

Example Files: NumDaysClass.7z

NumDaysClass.h


#ifndef NUM_DAYS_H_
#define NUM_DAYS_H_

class NumDays
{
private:
    double workHours;            // To hold a number of hours

public:
    NumDays(double hours = 0.0)       
    {    workHours = hours; }

    void setHours(double hours)       
    { workHours = hours; }

    void print();

    double getHours() const
    { return workHours; }

    double getDays() const
    { return workHours / 8; }

    // Overloaded operator functions
    NumDays operator + (const NumDays &);                // Overloaded +
    NumDays operator - (const NumDays &);                // Overloaded -
    NumDays operator ++();                                    // Overloaded Prefix ++                       
    NumDays operator ++(int);                                // Overloaded Postfix ++
    NumDays operator --();                                    // Overloaded Prefix --
    NumDays operator --(int);                                // Overloaded Postfix --
};

#endif

NumDaysClass.cpp


#include "NumDays.h"

#include <iostream>
using std::cout;

/* **********************************************************
            NumDays NumDays::operator +(const obj &)
   ********************************************************** */

NumDays NumDays::operator + (const NumDays &right)
{
    NumDays temp;
   
    temp.workHours = (workHours + right.workHours);

    return temp;
}

/* **********************************************************
            NumDays NumDays::operator -(const obj &)
   ********************************************************** */

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

    if (workHours < right.workHours)
    {
        temp.workHours = (right.workHours - workHours);
    }
    else
    {
        temp.workHours = (workHours - right.workHours);
    }
    return temp;
}

/* **********************************************************
            NumDays NumDays::operator ++() : Prefix ++
   ********************************************************** */

NumDays NumDays::operator ++()
{
    return ++workHours;
}

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

NumDays NumDays::operator ++(int)
{
    return workHours++;
}

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

NumDays NumDays::operator --()
{
    return --workHours;
}

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

NumDays NumDays::operator --(int)
{
    return workHours--;
}

/* **********************************************************
            NumDays::print()
    Outputs the hour(s) and day(s) worked to screen.
   ********************************************************** */

void NumDays::print()
{
    cout << "Total: " << (getHours()) << " hour(s) or "
          << getDays() << " day(s).\n\n";
}

NumDaysDm.cpp


#include "NumDays.h"

#include <iomanip>
using std::fixed;
using std::showpoint;
using std::setprecision;

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

int main()
{
    NumDays thisWeek(26);
    NumDays lastWeek(15);
    NumDays total;

    cout << "YAMAGATA 4th JUNIOR HIGH SCHOOL BIWEEKLY WORKSHEET SUMMARY\n\n";

    // Demonstrating the overloaded postfix ++, -- operators
    cout << fixed << showpoint << setprecision(2);
    cout << "You worked " << thisWeek.getHours() << " hour(s) in total this week.\n";
    cout << "This makes " << thisWeek.getDays() << " day(s) of work.\n\n";

    cout << "We increased this amount by 1 hour\n";
    thisWeek++;
    thisWeek.print();

    cout << "We detucted 1 hour from this amount\n";
    thisWeek--;
    thisWeek.print();

    // Demonstrating the overloaded prefix ++, --, + and - operators
    cout << "You worked " << lastWeek.getHours() << " hour(s) in total last week.\n";
    cout << "This makes " << lastWeek.getDays() << " day(s) of work.\n\n";

    cout << "We increased this amount by 1 hour\n";
    ++lastWeek;
    lastWeek.print();

    cout << "We detucted 1 hour from this amount\n";
    --lastWeek;
    lastWeek.print();

    cout << "This week and last week you worked\n";
    total = thisWeek + lastWeek;
    total.print();

    cout << "The difference in hours and days is\n";
    total = thisWeek - lastWeek;
    total.print();

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

Example Output: