Monday, August 28, 2017

Programming Challenge 13.9 - Population

Example Files: Population.h
                          Population.cpp
                          PopulationDemo.cpp

Population.h


/* Population.h - Specification file of the Population class. */

#ifndef POPULATION_H
#define POPULATION_H

#include <string>

using std::string;

class Population
{
    private:
       string townName;                    // The name of a town
        double birthRate;                    // The number of births p.A.
        double deathRate;                    // The number of deaths p.A.
        double startingPopulation;        // The starting population
        int     numYears;
        double populationIncrease;        // Holds the population increase in percent
        double populationDecrease;        // Holds the population decrease in percent
        double populationNetGrowth;   // Holds the net population growth in percent

    public:
        Population()                        // Default constructor
        {
            townName = " ";
            birthRate = 0.0;
            deathRate = 0.0;
            populationIncrease = 0.0;
            populationDecrease = 0.0;
        }
      
        // Mutators
        void setTownName(string tName);
        void setNumYears(int nYears);
        void setStartingPopulation(double sPop);
        void setBirthRate(double bRate);
        void setDeathRate(double dRate);
        void calcPopulationIncrease(double sPop, double bRate, int numYrs);
        void calcPopulationDecrease(double sPop, double dRate, int numYrs);

        // Accessors
        string getTownName() const
        { return townName; }

        double getStartingPopulation() const
        { return startingPopulation; }

        double getBirthRate() const
        { return birthRate; }

        double getDeathRate() const
        { return deathRate; }

        double getPopulationIncrease() const
        { return populationIncrease / 100.0; }

        double getPopulationDecrease() const
        { return populationDecrease / 100.0; }

        int getNumYears() const
        { return numYears; }

        double getNetGrowth() const
        { return (populationIncrease / 100.0) - (populationDecrease / 100.0); }

        double getNewPopulation() const
        { return (populationIncrease - populationDecrease) + startingPopulation; }
};
#endif

Population.cpp


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

#include <cmath>
#include "Population.h"

/* **********************************************************
            Population::setTownName
    Assigns a value to the setTownName member variable. If the
    field is not empty, the name passed to it is used, else a
    default name is assigned to it.
    ********************************************************** */

void Population::setTownName(string tName)
{
    if (!tName.empty())
    {
        townName = tName;
    }
    else
    {
        townName = "Terrania";
    }
}

/* **********************************************************
            Population::setStartingPopulation
    Assigns a value to the startingPopulation member variable.
    If the value is greater than 0, the value passed to it is
    used, else the variable is set to 1,000.
    ********************************************************** */
void Population::setStartingPopulation(double sPop)
{
    if (sPop > 0.0)
    {
        startingPopulation = sPop;
    }
    else
    {
        startingPopulation = 1000.0;
    }
}

/* **********************************************************
            Population::setBirthRate
    Assigns a value to the birthRate member variable. If the
    value is greater than 0, the value passed to it is used,
    else the variable is set to 2.48.
    ********************************************************** */

void Population::setBirthRate(double bRate)
{
    if (bRate > 0.0 && bRate <= 100.0)
    {
        birthRate = bRate;
    }
    else
    {
        birthRate = 2.48;
    }
}

/* **********************************************************
            Population::setDeathRate
    Assigns a value to the deathRate member variable. If the
    value is greater than 0 and lower than 100, the value
    passed to it is used, else the variable is set to 1.15.
    ********************************************************** */

void Population::setDeathRate(double dRate)
{
    if (dRate > 0.0 && dRate <= 100.0)
    {
        deathRate = dRate;
    }
    else
    {
        deathRate = 1.15;
    }
}

/* **********************************************************
            Population::setNumYears
    Assigns a value to the numYears member variable. If the
    value is greater 0, the value passed to it is used, else
    the variable is assigned a default value of 5.
   ********************************************************** */

void Population::setNumYears(int nYears)
{
    if (nYears > 0)
    {
        numYears = nYears;
    }
    else
    {
        numYears = 5;
    }
}

/* **********************************************************
            Population::calcPopulationIncrease
    Calculates the population increase taking place over a
    period of time.
   ********************************************************** */

void Population::calcPopulationIncrease(double sPop, double bRate, int numYrs)
{
    populationIncrease += bRate * (pow((1 + bRate / 100.0), numYrs) * 10);
}

/* **********************************************************
            Population::calcPopulationDecrease
    Calculates the population decrease taking place over a
    period of time.
    ********************************************************** */

void Population::calcPopulationDecrease(double sPop, double dRate, int numYrs)
{
    populationDecrease += dRate * (pow((1 - dRate / 100.0), numYrs) * 10);
}

PopulationDemo.cpp


 /* PopulationDemo.cpp - This program demonstrates the Population class. */

#include <string>
#include <iostream>
#include <iomanip>
#include "Population.h"

using std::cin;
using std::cout;
using std::fixed;
using std::showpoint;
using std::setprecision;

char tryAgain();
void getData(Population &);
void calcPopChange(const Population);
void displayStartData(const Population);
void displayPopChange(Population);

int main()
{
    Population populous;
  
    char again = ' ';

    cout << "POPULOUS - Population Statistics Calculator\n";

    do
    {
        getData(populous);
        displayStartData(populous);
        calcPopChange(populous);

        again = tryAgain();

        if (toupper(again) == 'N')
        {
            cout << "\nThank you for trying Populous! Have a nice day!";
        }

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

    cin.ignore();

    return 0;
}

/* **********************************************************
    getData (accepts a reference to a Circle object)
    The user is asked to input the following information:

        * The town name (if the user leaves this field blank,
          a default name is used)
        * The starting population (if the user enters 0, a
          default value of 1,000 is used)
        * The number of births (if the user enters 0, a default
          value of 2.48 is used)
        * The number of deaths (if the user enters 0, a default
          value of 1.15 is used)
        * The number of years to calucalate population change
          (If the user enters 0, a default value of 5 is used)
    ********************************************************** */

void getData(Population &populous)
{
    string tName = " ";
    double bRate = 0.0;
    double dRate = 0.0;
    double sPop = 0.0;
    int    numYrs = 0;

    cout << "\nEnter the name of your town: ";
    std::getline(cin, tName);
    populous.setTownName(tName);

    cout << "Enter the number of people currently living in your town: ";
    cin >> sPop;
    populous.setStartingPopulation(sPop);

    cout << "Enter the annual birth rate of your town [Ex.: 2.48%]: ";
    cin >> bRate;
    populous.setBirthRate(bRate);

    cout << "Enter the annual death rate of your town [Ex.: 1.15%]: ";
    cin >> dRate;
    populous.setDeathRate(dRate);

    cout << "Enter the number of years you wish the simulation to run: ";
    cin >> numYrs;
    populous.setNumYears(numYrs);
}

/* **********************************************************
   calcPopChange (accepts a Population object)
    This function calculates the population increase and
    decrease over a period of time.
   ********************************************************** */

void calcPopChange(Population populous)
{
    for (int i = 0; i < populous.getNumYears(); ++i)
    {
        populous.calcPopulationIncrease(populous.getStartingPopulation(), populous.getBirthRate(), i);
        populous.calcPopulationDecrease(populous.getStartingPopulation(), populous.getDeathRate(), i);

        displayPopChange(populous);
    }
}

/* **********************************************************
   displayStartData (accepts a const Population object)
    This function displays the initial values set by the user.
   ********************************************************** */

void displayStartData(const Population populous)
{
    cout << "\nWelcome to "      << populous.getTownName() << " Administrator!\n"
          << "This is the population you are starting with:\n"
          << "Number of people: " << populous.getStartingPopulation() << "\n"
          << "Number of births: " << populous.getBirthRate() << "% p.A.\n"
          << "Number of deaths: " << populous.getDeathRate() << "% p.A.\n";
}

/* **********************************************************
   displayPopChange (accepts a const Population object)
    This function displays the population change over a period
    of time.
   ********************************************************** */

void displayPopChange(Population populous)
{
    static int i = 0;

    cout << "\nIn year " <<  (i += 1)   << " the population of "
          << populous.getTownName()       << " has grown to "
          << populous.getNewPopulation() << " people.\n\n";

    cout << fixed << showpoint << setprecision(2);
    cout << "Birth Rate: " << populous.getPopulationIncrease() << "%\n";
    cout << "Death Rate: " << populous.getPopulationDecrease() << "%\n";
    cout << "Net Growth: " << populous.getNetGrowth()              << "%\n";
}

/* **********************************************************
    Definition: tryAgain

    This function asks the user if he or she wishes to try
    again. This decision is returned.
    ********************************************************** */

char tryAgain()
{
    char again = ' ';

    cout << "\nDo you wish to try this again? ";
    cin >> again;
    cin.ignore();

    /* Input validation */
    while (toupper(again) != 'Y' && toupper(again) != 'N')
    {
        cout << "\nDo you wish to try this again? ";
        cin >> again;
    }

    return toupper(again);
}

Example Output: 



Wednesday, August 23, 2017

Programming Challenge 13.8 - Circle Class

Example Files: UtilityCls.h
                          CircleClass.h
                          CircleClassDemo.cpp

CircleClass.h


#ifndef CIRCLE_H
#define CIRCLE_H

#include <cmath>

class Circle
{
    private:
        double radius;        // Radius of the circle
        double pi;  
     
    public:
        Circle()
        {
            radius = 0.0;
            pi = 3.14159;
        }

        // Sets the radius of the circle
        void setRadius(double r)       
        {
            radius = r;
        }

        // Gets the radius of the circle
        double getRadius() const       
        { return radius; }

        // Calculates the area of the circle
        double getArea() const           
        { return pi * pow(radius, 2.0); }

        // Calculates the circle's diameter
        double getDiameter() const               
        { return radius * 2.0; }

        // Calculates the circle's circumference
        double getCircumference() const       
        { return 2.0 * (pi * radius); }
};
#endif

CircleClassDemo.cpp


/* CircleClass.cpp - Circle Class demo. */

#include <iomanip>
#include <iostream>
#include <string>
#include "CircleClass.h"
#include "UtilityCls.h"

using std::cin;
using std::cout;
using std::fixed;
using std::showpoint;
using std::setprecision;
using std::setw;

void displayInstructions();
void displayMenu();
void getRadius(Circle &);
void menu(Circle &);

int main()
{
    Circle uCircle;
    menu(uCircle);

    cin.get();
    cin.ignore();

    return 0;
}
/* **********************************************************
    displayMenu (void)
    This function displays the menu options.
   ********************************************************** */

void displayMenu()
{
    cout << "\nCIRCLE CALCULATOR\n\n"
          << "V] VIEW INSTRUCTIONS\n"
          << "E] ENTER RADIUS OF CIRCLE\n"
          << "A] CALCULATE AREA\n"
          << "D] CALCULATE DIAMETER\n"
          << "C] CALCULATE CIRCUMFERENCE\n"
          << "F] CALCULATE AREA / DIAMETER / CIRCUMFERENCE\n"
          << "Q] QUIT\n\n"
          << "Choice: ";
}

/* **********************************************************
    displayInstructions (void)
    This function displays the program instructions.
   ********************************************************** */

void displayInstructions()
{
    cout << "WELCOME TO THE CIRCLE CALCULATOR.\n\n"
          << "To begin using with this program, select E] from the main menu to enter the radius\n"
          << "of your circle. Once done, you are able to select between the following menu items:\n\n"
          << "A] To calculate the area of your circle          (formula: PI * radius * radius)\n"
          << "D] To calculate the diameter of your circle      (formula: radius * 2.0)\n"
          << "C] To calculate the circumference of your circle (formula: 2.0 * PI * radius)\n\n"
         << "F] To calculate the area, diameter and circumference of your circle\n\n";
    cout << "While in main menu, you are able to change the radius of the circle at any time,\n"
          << "then perform one calculation [A, D, C] or [F] for all calculations.\n"
          << "To quit this program you should enter 'Q' or 'q'\n\n";
}
/* **********************************************************
    menu (accepts a reference to a Circle object)
    This function holds the main menu of the program.
   ********************************************************** */

void menu(Circle &uCircle)
{
    char choice = ' ';

    do
    {
        displayMenu();  
        cin >> choice;
        cout << "\n";
      
        switch (choice)
        {
            case 'V':
            case 'v':
            {
                displayInstructions();
                pauseSytem();
                clearScreen();
            } break;

            case 'E':
            case 'e':
            {
                getRadius(uCircle);
                pauseSytem();
                clearScreen();
            } break;

            case 'A':
            case 'a':
            {
                cout << setw(16) << "The radius of your circle is: "
                      << setw(14) << uCircle.getRadius() << setw(5) << "   feet.\n";
                cout << setw(20) << "The area of your circle is "
                      << setw(19) << uCircle.getArea() << " square feet.\n";
                pauseSytem();
                clearScreen();
            } break;

            case 'D':
            case 'd':
            {
                cout << setw(16) << "The radius of your circle is: "
                      << setw(14) << uCircle.getRadius() << setw(5) << "   feet.\n";
                cout << setw(20) << "The Diameter of your circle is: "
                      << setw(11) << uCircle.getDiameter() << setw(4) << " feet.\n";
                pauseSytem();
                clearScreen();
            } break;

            case 'C':
            case 'c':
            {
                cout << setw(16) << "The radius of your circle is: "
                      << setw(14) << uCircle.getRadius() << setw(5) << "   feet.\n";
                cout << setw(20) << "The Circumference of your circle is "
                      << setw(10) << uCircle.getCircumference() << " feet.\n";
                pauseSytem();
                clearScreen();
            } break;

            case 'F':
            case 'f':
            {
                cout << setw(16) << "The radius of your circle is: "
                      << setw(14) << uCircle.getRadius() << setw(5) << "   feet.\n";
                cout << setw(20) << "The area of your circle is "
                      << setw(19) << uCircle.getArea() << " square feet.\n"
                      << setw(20) << "The Diameter of your circle is "
                      << setw(12) << uCircle.getDiameter() << setw(10) << " feet.\n"
                      << setw(20) << "The Circumference of your circle is "
                      << setw(10) << uCircle.getCircumference() << " feet.\n";
                pauseSytem();
                clearScreen();
            } break;

            case 'Q':
            case 'q':
            {
                cout << "Thank you for trying this program! Have a nice day!";
            }
        }
    } while (toupper(choice) != 'Q');
}

/* **********************************************************
    getRadius (accepts a reference to a Circle object)
    The user is asked to enter the radius of a circle. If the
    radius is lower than or equal to 0, the user is asked to
    repeat the input. Else, the value is passed to the member
    variable of the circle object.
   ********************************************************** */

void getRadius(Circle &uCircle)
{
    double radius = 0.0;

    cout << "Enter the radius of a circle: ";
    cin >> radius;

    while (radius <= 0.0)
    {
        cout << "Enter radius greater than 0: ";
        cin >> radius;
    }

    uCircle.setRadius(radius);
}

Example Output:









Tuesday, August 22, 2017

Programming Challenge 13.7 - TestScores Class

Example Files: TestScoresClass.h
                          TestScoresClassDemo.cpp

TestScoresClass.h


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

#ifndef TEST_SCORE_CLASS_H
#define TEST_SCORE_CLASS_H

class TestScore
{
    private:
        int scoreOne;        // Score one
        int scoreTwo;        // Score two
        int scoreThree;    // Score three   
        double average;    // Average score

    public:
        TestScore()            // Default constructor
        {
            scoreOne = 0;
            scoreTwo = 0;
            scoreThree = 0;
            average = 0.0;
        }

        // Mutators
        void setScores(int scO, int scT, int scTh)
        {
                scoreOne = scO;
                scoreTwo = scT;
                scoreThree = scTh;
        }

        void setAverage()
        {
            average = (scoreOne + scoreTwo + scoreThree) / 3.0;   
        }

        // Accessors
        int getScoreOne() const
        { return scoreOne; }

        int getScoreTwo() const
        { return scoreTwo; }

        int getScoreThree() const
        { return scoreThree; }

        double getAverage() const
        { return average; }
};
#endif

TestScoresClassDemo.cpp


/* TestScoreClass.cpp - This program demonstrates the TestScoreClass class. */

#include "TestScoresClass.h"
#include <iomanip>
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::setw;
using std::setprecision;
using std::showpoint;
using std::fixed;

void getScores(TestScore &);
void display(const TestScore);

int main()
{
    TestScore scores;

    cout << "AVERAGE TEST SCORE DEMO\n\n"
          << "Enter three test scores and I will calculate the average for you\n\n";

    getScores(scores);
    scores.setAverage();
    display(scores);

    cout << "\n\nThank you for trying this demo! Have a nice day.";
    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
    getScores (accepts a reference to a TestScore object)
    The user is asked to enter three test scores. The scores
    are stored in the appropriate TestScore object member
    variables.
   ********************************************************** */

void getScores(TestScore &scores)
{
    int scoreO = 0;
    int scoreT = 0;
    int scoreTh = 0;

    cout << "Score 1: ";
    cin >> scoreO;

    while (scoreO < 1 || scoreO > 100)
    {
        cout << "Score 1: ";
        cin >> scoreO;
    }

    cout << "Score 2: ";
    cin >> scoreT;

    while (scoreT < 1 || scoreT > 100)
    {
        cout << "Score 2: ";
        cin >> scoreT;
    }

    cout << "Score 3: ";
    cin >> scoreTh;

    while (scoreTh < 1 || scoreTh > 100)
    {
        cout << "Score 3: ";
        cin >> scoreTh;
    }

    scores.setScores(scoreO, scoreT, scoreTh);
}

/* **********************************************************
    display (accepts a const TestScore object)
    This function displays the test scores and the average.
   ********************************************************** */

void display(const TestScore scores)
{
    cout << "\nThese are your test scores:\n\n";
    cout << "Score 1: " << scores.getScoreOne()   << "\n"
          << "Score 2: " << scores.getScoreTwo()   << "\n"
          << "Score 3: " << scores.getScoreThree() << "\n";

    cout << fixed << showpoint << setprecision(2);
    cout << "\nYou reached an average score of: " << scores.getAverage() << "%";
}

Example Output:




Monday, August 21, 2017

Programming Challenge 13.6 - Inventory Class

Example Files: InventoryClass.h
                          InventoryClass.cpp
                          InventoryClassDemo.cpp

IventoryClass.h


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

#ifndef INVENTORY_CLASS_H
#define INVENTORY_CLASS_H

class Inventory
{
    private:
        int itemNumber;      // The item number
        int quantity;             // Number of items on hand
        double cost;             // Wholesale per-unit cost of the item
        double totalCost;     // Total cost of the item

    public:
        // Default constructor
        Inventory()
        {
            itemNumber = 0;
            quantity = 0;
            cost = 0.0;
            totalCost = 0.0;
        }

        // Constructor accepting arguments for itemID, quantity and cost
        Inventory(int iID, int iQty, double iCost)
        {
            itemNumber = iID;
            quantity = iQty;
            cost = iCost;
        }

        // Mutators
        bool setItemNumber(int iID);
        bool setQuantity(int iQty);
        bool setCost(double iCost);
        void setTotalCost(double iCost);

        // Accessors
        int getItemNumber() const
        { return itemNumber; }

        int getQuantity() const
        { return quantity; }

        double getCost() const
        { return cost; }

        double getTotalCost() const
        { return totalCost; }   
};
#endif

InventoryClass.cpp


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

#include "InventoryClass.h"
#include <string>
#include <iostream>

/* **********************************************************
                Inventory::setItemNumber
    Sets the value of the member variable itemNumber.
   ********************************************************** */

bool Inventory::setItemNumber(int iID)
{
    if (iID > 0)
    {
        itemNumber = iID;
        return true;
    }
    else
    {
        std::cout << "\nInvalid item ID.\n\n";
    }

    return false;
}

/* **********************************************************
                Inventory::setQuantity
    Sets the value of the member variable quantity.
   ********************************************************** */

bool Inventory::setQuantity(int iQty)
{
    if (iQty > 0)
    {
        quantity = iQty;
        return true;
    }
    else
    {
        std::cout << "\nItem quantity cannot be 0 or negative.\n\n";
    }

    return false;
}

/* **********************************************************
                Inventory::setCost
    Sets the value of the member variable cost.
   ********************************************************** */

bool Inventory::setCost(double iCost)
{
    if (iCost > 0)
    {
        cost = iCost;
        return true;
    }
    else
    {
        std::cout << "\nWholesale cost cannot be 0 or negative.\n";
    }

    return false;
}

/* **********************************************************
                Inventory::setItemNumber
    Sets the value of the member variable totalCost. The total
    cost is calculated as quantity times cost.
   ********************************************************** */

void Inventory::setTotalCost(double iCost)
{
    totalCost = (quantity * iCost);
}

InventoryClassDemo.cpp


/* InventoryClass.cpp - This program demonstrates the InventoryClass class. */

#include "InventoryClass.h"
#include <iomanip>
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::setw;
using std::setprecision;
using std::showpoint;
using std::fixed;

void getItemInfo(Inventory *, const int);
void displayItems(const Inventory *, const int);

int main()
{
    const int NUM_ITEMS = 2;
    Inventory items[NUM_ITEMS];

    cout << "CYBER CITY BATTLE-CHIP WAREHOUSE\n\n";

    getItemInfo(items, NUM_ITEMS);

    for (int i = 0; i < NUM_ITEMS; i++)
    {
        items[i].setTotalCost(items[i].getCost());
    }

    displayItems(items, NUM_ITEMS);

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

/* **********************************************************
    getItemInfo (accepts an array of RetailItem objects and
    an integer value holding the number of items as arguments)
    It asks the user to enter an item ID, the quantity on hand
    and the cost of an item.
   ********************************************************** */

void getItemInfo(Inventory *items, const int NUM_ITEMS)
{
    int    itemID = 0;
    int    itemQuantity = 0;
    double itemCost = 0.0;

    for (int i = 0; i < NUM_ITEMS; i++)
    {
        cout << "Enter Item Number: " << setw(5) << "\n";
        cin >> itemID;
       
        while (!items[i].setItemNumber(itemID))
        {
            cout << "Enter Item Number: " << setw(5) << "\n";
            cin >> itemID;
        }

        cout << "Enter Quantity: " << setw(4) << "\n";
        cin >> itemQuantity;

        while (!items[i].setQuantity(itemQuantity))
        {
            cout << "Enter Quantity: " << setw(5) << "\n";
            cin >> itemQuantity;
        }

       cout << "Enter Wholesale Cost: " << setw(4) << "\n";
        cin >> itemCost;

        while (!items[i].setCost(itemCost))
        {
            cout << "Enter Wholesale Cost: " << setw(5) << "\n";
            cin >> itemCost;
        }
        cout << "\n";
    }
}

/* **********************************************************
    displayItems (accepts an array of RetailItem objects and
    an integer value holding the number of items as arguments)
    It displays information about the items.
   ********************************************************** */

void displayItems(const Inventory *items, const int NUM_ITEMS)
{
    cout << "\nCYBER CITY BATTLE-CHIP WAREHOUSE\n\n"
         << setw(5)  << "Item ID"
          << setw(19) << "Units on Hand" << setw(16)
          << setw(13) << "Cost" << setw(13)
          << setw(20) << "Total Cost\n";
    cout << "==========================================================\n";

    for (int i = 0; i < NUM_ITEMS; i++)
    {
        cout << setw(7)  << items[i].getItemNumber()
              << setw(19) << items[i].getQuantity();
        cout << showpoint << fixed << setprecision(2);
        cout << setw(13) << items[i].getCost()
              << setw(19) << items[i].getTotalCost() << "\n";
    }
}

Example Output:





Programming Challenge 13.5 - RetailItem Class

Example Files: RetailItem.h
                         RetailItem.cpp

RetailItem.h


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

#ifndef RETAILITEM_H
#define RETAILITEM_H

#include <string>

using std::string;

class RetailItem
{
    private:
        string description;        // The item description
        int unitsOnHand;            // The number of units at hand
        double price;                // The item cost

    public:
        // Constructor accepting arguments for each member variable
        RetailItem(string descr, int units, double cost)
        {
            description = descr;
            unitsOnHand = units;
            price = cost;
        }

        // Mutators
        void setDescription(string d)
        { description = d; }

        void setUnitsOnHand(int u)
        { unitsOnHand = u; }

        void setPrice(double c)
        { price = c; }

        // Accessors
        string getDescription() const
        { return description; }

        int getUnitsOnHand() const
        { return unitsOnHand; }

        double getPrice() const
        { return price; }
};
#endif

RetailItem.cpp


/* RetailItem.cpp - This program demonstrates the RetailItem class. */

#include "RetailItem.h"
#include <iomanip>
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::setw;
using std::setprecision;
using std::fixed;

void displayItems(RetailItem *, const int);

int main()
{
    const int NUM_ITEMS = 3;
    RetailItem items[NUM_ITEMS] = { { "Jacket", 12, 59.95 },
                                                                { "Designer Jeans", 40, 34.95 },
                                                                { "Shirt", 20, 24.95 } };

    displayItems(items, NUM_ITEMS);

    cin.get();
    return 0;
}

/* **********************************************************
    displayItems (accepts an array of RetailItem objects and
    an integer value holding the number of items as arguments)
    It displays information about the items.
   ********************************************************** */

void displayItems(RetailItem *items, const int NUM_ITEMS)
{
    cout << "\nCYBER CITY NET-BATTLER FASHION STORE\n\n"
         << setw(29) << "Inventory Item"
          << setw(19) << "Units on Hand" << setw(16)
          << setw(13) << "Cost\n";
    cout << "============================================================\n";

    for (int i = 0; i < NUM_ITEMS; i++)
    {
        cout << "ITEM # " << (i + 1) << setw(21) << items[i].getDescription()
                                                        << setw(19) << items[i].getUnitsOnHand()
                                                        << setw(12) << items[i].getPrice() << "\n";
    }
}

Example Output:



Sunday, August 20, 2017

Programming Challenge 13.4 [9E] - Patient Charges

Example Files: Patient.h
                          Procedure.h
                          PatientCharges.cpp
                          PatientChargesDemo.cpp

Patient.h


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

#ifndef PATIENT_H
#define PATIENT_H

#include <string>

using std::string;

class Patient
{
    private:
        string name;                    // Name of the patient
        string address;                // Patient's address
        string phoneNumber;            // Patient's telephone number
        string emcName;                // Name of the emergency contact person
        string emcPhoneNumber;        // Telephone number of the emergency contact person   

    public:
        // Constructor accepting arguments for all Procedure members
        Patient(string pN, string pAddr, string pPhone, string emcN, string emcPhone)
        {
            name = pN;
            address = pAddr;
            phoneNumber = pPhone;
            emcName = emcN;
            emcPhoneNumber = emcPhone;
        }

        // Destructor
        ~Patient()
        {}
       
        // Mutators
        void setName(string pN)
        { name = pN; }

        void setAddress(string pAddr)
        { address = pAddr; }
       
        void setPhoneNumber(string pPhone)
        { phoneNumber = pPhone; }

        void setEMCName(string emcN)
        { emcName = emcN; }

        void setEMCPhoneNumber(string emcPhone)
        { emcPhoneNumber = emcPhone; }

        // Accessors
        string getName() const
        { return name; }

        string getAddress() const
        { return address; }
       
        string getPhoneNumber() const
        { return phoneNumber; }

        string getEMCName() const
        { return emcName; }

        string getEMCPhoneNumber() const
        { return emcPhoneNumber; }

        void display() const;
};
#endif

Procedure.h


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

#ifndef PROCEDURE_H
#define PROCEDURE_H

#include <string>
#include <iostream>

using std::string;

class Procedure
{
    private:
        string procedureName;            // Name of the procedure
        string dateToday;                    // Today's date
        string practitionerName;        // Name of the practitioner
        double charge;                        // Holding the charges for each procedure
        double total;                        // Holding the total charges

    public:
        // Default constructor
        Procedure()       
        {   
            procedureName = "";
            dateToday = "";
            practitionerName = "";
            charge = 0.0;
            total = 0.0;
        }

        // Destructor
        ~Procedure()
        {}

        // Constructor accepting arguments for all Procedure members
        Procedure(string procName, string dateT, string practName, double procChrg)   
        {
            procedureName = procName;
            dateToday = dateT;
            practitionerName = practName;
            charge = procChrg;
            total = procChrg;
        }

        // Mutators
        void setProcedureName(string proc)
        { procedureName = proc; }

        void setDateToday(string dateT)
        { dateToday = dateT; }

        void setPractitionerName(string practName)
        { practitionerName = practName; }

        void setTotal(double chrg)
        { total += chrg; }

        // Accessors
        string getProcedureName() const
        { return procedureName; }

        string getDateToday() const
        { return dateToday; }

        string getPractitionerName() const
        { return practitionerName; }

        double getCharge() const
        { return charge; }

        double getTotal() const
        { return total; }

        void display() const;
        void displayTotal() const;

};
#endif

PatientCharges.cpp


/* PatientCharges.cpp - Implementation file for the Patient and Procedure
    class files. */

#include "Procedure.h"
#include "Patient.h"

#include <string>
#include <iomanip>

using std::cout;
using std::fixed;
using std::setprecision;
using std::showpoint;
using std::setw;

/* **********************************************************
                Patient::display
    This function displays information about a patient.
   ********************************************************** */

void Patient::display() const
{
         cout << "\n\nPATIENT INFORMATION\n\n"
              << "Patient Name: "     << setw(15) << getName()               << "\n"
                 << "Address: "          << setw(45) << getAddress()           << "\n"
                 << "Phone Number: "     << setw(13) << getPhoneNumber()    << "\n"
                 << "EMC Contact: "         << setw(15) << getEMCName()           << "\n"
                 << "EMC Phone #: "         << setw(14) << getEMCPhoneNumber() << "\n\n";
}

/* **********************************************************
                Procedure::displayProcedures
    This function displays information about the procedures
    performed on a patient, the name of the procedure, the
    date it was performed on, the practitioner performing it,
    and the charge for that procedure.
   ********************************************************** */

void Procedure::display() const
{
    cout << setw(16) << "Procedure Name: " << getProcedureName()        << "\n"
          << setw(16) << "Date: "               << getDateToday()            << "\n"
          << setw(16) << "Practitioner: "    << getPractitionerName() << "\n"
          << setw(18) << "Charge: $ "           << getCharge()               << "\n\n";
}

/* **********************************************************
                Procedure::displayTotal
    This function displays the total charges.
   ********************************************************** */

void Procedure::displayTotal() const
{
    cout << setw(18) << "Total Charge: $ " << total;
}

PatientChargesDemo.cpp


/* PatientChargesDemo.cpp - This program demonstrates the Patient and Procedure
    classes.    */

#include <string>
#include <iostream>
#include <iomanip>
#include "Patient.h"
#include "Procedure.h"

using std::cout;
using std::cin;
using std::setw;

void calcCharges(Procedure &, const Procedure *, const int);
void displayInfo(const Procedure *, const int);

int main()
{
    const int NUM_PROCEDURES = 3;

    Procedure charges;

    // Patient object initialized with
    Patient patientInfo("Lo Wen, Allen", "22 McKenzie Drive, Upper King, WA 6630",
                              "1244-124565", "Leona, Allen", "2484-241565");

    // Array of three Procedure objects
    Procedure procedures[NUM_PROCEDURES] = { { "Physical Exam", "17.08.2017", "Dr. Irvine", 250.00 },
                                                          { "X-Ray", "17.08.2017", "Dr. Jones", 500.00 },
                                                          { "Blood Test", "17.08.2017", "Dr. Smith", 200.00 } };
   
    cout << "Mt. RAKUTEI HOSPITAL - PATIENT BILLING SYSTEM\n\n";

    patientInfo.display();
    calcCharges(charges, procedures, NUM_PROCEDURES);
    displayInfo(procedures, NUM_PROCEDURES);
    charges.displayTotal();

    cin.ignore();
    return 0;
}

/* **********************************************************
    calcCharges (accepts a Procedure object passed to it by
                     reference, a const Procedure array object,
                     and an integer holding the total number of
                     charges)
    It calculates the total patient charges.
   ********************************************************** */

void calcCharges(Procedure &charges, const Procedure *procedures, const int NUM_CHARGES)
{
    for (int i = 0; i < NUM_CHARGES; i++)
    {
        charges.setTotal(procedures[i].getCharge());               
    }
}

/* **********************************************************
    displayInfo (accepts a const Procedure array object, and
    an integer value holding the total number of procedures)
    It displays all information about the procedures performed
    on the patient.
   ********************************************************** */

void displayInfo(const Procedure *procedures, const int NUM_PROCEDURES)
{
    cout << "MEDICAL PROCEDURES\n\n";
    cout << std::setprecision(2) << std::showpoint << std::fixed;
    for (int i = 0; i < NUM_PROCEDURES; i++)
    {
        procedures[i].display();
    }
}

Example Output:



Thursday, August 17, 2017

Programming Challenge 13.4 [8E] - Personal Information Class

Example Files: PersonalInformation.h
                          PersonalInformation.cpp
                          PersonalInformationDemo.cpp


PersonalInformation.h


/* PersonalInformation.h - Specification file for the Personal Information class. */

#ifndef PERSONAL_INFORMATION_H
#define PERSONAL_INFORMATION_H

#include <array>
#include <string>

using std::string;
static constexpr int NUM_ITEMS = 2;

class Personal
{
    private:
        string name;                // Holds the name
        string address;            // Holding the address
        short int age;                // Holding the age
        string phoneNumber;        // Holding the telephone number

        static const std::array<Personal, NUM_ITEMS> friends;        // Array of class objects

    public:
        static constexpr int MAX_LEN = 25;        // Maximmum name and address length
        static constexpr int MAX_AGE = 85;        // Maximum age
        static constexpr int PNUM_LEN = 10;        // Maximum phone number length

        // Default Constructor
        Personal()   
        {
            name = "";
            address = "";
            age = 0;
            phoneNumber = "";
        }

        // Constructor accepting arguments for name, address, age and phone number
        Personal(string n, string addr, int a, string pNum)
        {
            name = n;
            address = addr;
            age = a;
            phoneNumber = pNum;
        }

        // Mutators
        bool setName(string);
        bool setAddress(string);
        bool setAge(short int);
        bool setPhoneNumber(string);

        // Accessors
        string getName() const
        { return name; }

        string getAddress() const
        { return address; }

        short int getAge() const
        { return age; }

        string getPhoneNumber() const
        { return phoneNumber; }

        void displayPersonalInfo() const;
        void displayFriendsInfo(std::array<Personal, NUM_ITEMS>) const;
};
#endif

PersonalInformation.cpp


/* PersonalInformation.cpp - Implementation file for the Personal
    Information class */

#include <array>
#include <iostream>
#include <iomanip>
#include <string>
#include "PersonalInformation.h"

/* **********************************************************
                Personal::friends
    This function initializes all array elements via default
    constructor.
   ********************************************************** */

const std::array<Personal, NUM_ITEMS> Personal::friends{ Personal() };

/* **********************************************************
                Personal::setName
    Assigns a value to the name member variable.
   ********************************************************** */

bool Personal::setName(string n)
{
    if (n.length() > 1 && n.length() < MAX_LEN)
    {
        name = n;
        return true;
    }
    else
    {
        std::cout << "\nName too short.\n";
    }

    return false;
}

/* **********************************************************
                Personal::setAddress
    Assigns a value to the address member variable.
   ********************************************************** */

bool Personal::setAddress(string addr)
{
    if (addr.length() > 1 && addr.length() < MAX_LEN)
    {
        address = addr;
        return true;
    }
    else
    {
        std::cout << "\nInvalid address format.\n";
    }

    return false;
}

/* **********************************************************
                Personal::setAge
    Assigns a value to the age member variable.
   ********************************************************** */

bool Personal::setAge(short int a)
{
    if (a > 0 && a <= MAX_AGE)
    {
        age = a;
        return true;
    }
    else
    {
        std::cout << "\nInvalid age.\n";
        return false;
    }

    return false;
}

/* **********************************************************
                Personal::setPhoneNumber
    Assigns an address to the phoneNumber member variable.
   ********************************************************** */

bool Personal::setPhoneNumber(string phone)
{
    if (phone[0] != '\0' && phone.size() <= PNUM_LEN)
    {
        phoneNumber = phone;
        return true;       
    }
    else
    {
        std::cout << "\nPhone number invalid.\n";
    }

    return false;
}

/* **********************************************************
                Personal::displayPersonalInfo
    Displays the personal information.
   ********************************************************** */

void Personal::displayPersonalInfo() const
{
    std::cout << "\n\nADDRESS BOOK - PERSONAL INFORMATION\n\n";
    std::cout << std::setw(14) << "Name: "              << std::setw(2) << getName() << "\n"
                 << std::setw(14) << "Address: "          << std::setw(2) << getAddress() << "\n"
                 << std::setw(14) << "Age: "              << std::setw(2) << getAge() << "\n"
                 << std::setw(14) << "Phone Number: " << std::setw(2) << getPhoneNumber() << "\n";
}

/* **********************************************************
                Personal::displayFriendsInfo
    This function accepts an array of class objects, holding
    personal information about two friends. This information
    is displayed.
   ********************************************************** */

void Personal::displayFriendsInfo(std::array<Personal, NUM_ITEMS> friends) const
{
    std::cout << "\n\nADDRESS BOOK - FRIENDS LIST\n\n";
    for (int i = 0; i < NUM_ITEMS; i++)
    {
        std::cout << std::setw(14) << "Name: "              << std::setw(2)    << friends[i].getName() << "\n"
                   << std::setw(14) << "Address: "          << std::setw(2)    << friends[i].getAddress() << "\n"
                  << std::setw(14) << "Age: "              << std::setw(2) << friends[i].getAge() << "\n"
                   << std::setw(14) << "Phone Number: " << std::setw(2) << friends[i].getPhoneNumber() << "\n\n";
    }
}

PersonalInformationDemo.cpp


/* PersonalInformationDemo - This function demonstrates the Personal Information class. */

#include <array>
#include <string>
#include <iostream>
#include <iomanip>
#include "PersonalInformation.h"

using std::array;
using std::cin;
using std::cout;
using std::getline;

void getInfo(array<Personal, NUM_ITEMS> &);

int main()
{
    Personal pInfo("Yuki, Mori", "Hachinohe-shi, 4-choume, 3-4, Mansion 5F", 39, "0178-*****");
    std::array<Personal, NUM_ITEMS> friends;        // Declare an array of class objects

    cout << "WELCOME TO YOUR PERSONAL INFORMATION BUTLER\n\n"
          << "Please enter the following information about your " << NUM_ITEMS << " friends:\n";

    getInfo(friends);
    pInfo.displayPersonalInfo();
    pInfo.displayFriendsInfo(friends);
   
    cin.ignore();
    cin.get();
    return 0;
}

/* **********************************************************
    Function getInfo (accepts an array of class objects)

    The user to enter information about his or her friends or
    family members. This information is validated. If valid,
    the information is stored in the member variables, else
    the user is asked to repeat the input.
   ********************************************************** */

void getInfo(array<Personal, NUM_ITEMS> &friends)
{
    bool validInput = false;
    string name = "";
    string address = "";
    short int age = 0;
    string phone = "";

    for (int i = 0; i < NUM_ITEMS; i++)
    {
        cout << "\nEnter your friends name: ";
        getline(cin, name);

        while (!friends[i].setName(name))
        {
            cout << "Enter your friends name: ";
            getline(cin, name);
        }

        cout << "Enter your friends address: ";
        getline(cin, address);

        while (!friends[i].setAddress(address))
        {
            cout << "Enter your friends address: ";
            getline(cin, address);
        }

        cout << "Enter your friends age: ";
        cin >> age;

        do
        {
            if (cin.fail())
            {
                cin.clear();
                cin.ignore();
                cout << "Enter your friends age: ";
                cin >> age;
            }
            else
            {
                validInput = true;
            }
        } while (validInput == false);

        while (!friends[i].setAge(age))
        {
            cout << "\nEnter your friends age: ";
            cin >> age;
        }

        cin.ignore();
        cout << "Enter your friends phone number: ";
        getline(cin, phone);

        while (!friends[i].setPhoneNumber(phone))
        {
            cout << "Enter your friends phone number: ";
            cin.clear();
            getline(cin, phone);
        }
    }
}

Example Output: