Monday, October 9, 2017

Programming Challenge 13.17 - Cash Register

Example Files: CashRegister.h
                          InventoryItem.h
                          ShoppingBasket.h
                          CashRegister.cpp
                          CashRegisterDm.cpp                       

CashRegister.h


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

#ifndef CASH_REGISTER_H
#define CASH_REGISTER_H

#include "InventoryItem.h"

class CashRegister
{
    private:
        int    quantity;            // Item quantity to be bought
        double cost;                // Cost of the item
        double markup;                // Markup percentage (30%)
        double taxRate;            // Tax rate (6%)
        double unitPrice;            // The unit price of an item
        double salesTax;            // The sales tax (6%)
        double taxTotal;            // The tax total (sales tax + markup)
        double subTotal;            // The subtotal (markup + cost)
        double total;                // The grand-total

    public:
        CashRegister(double iMarkup = 0.30, double rate = 0.06)
        {
            markup = iMarkup;
            taxRate = rate;

            unitPrice = 0.0;
            salesTax = 0.0;
            subTotal = 0.0;
            taxTotal = 0.0;
            total = 0.0;
        }

        // Accessors
        void setCost(const Inventory item);
        bool isQuantity(Inventory item, int iQty);
        void updateRegister();
        void updateUnits(Inventory &item);
        void displayReceipt();

        // Mutators
        double getCost() const
        { return cost; }

        double getUnitPrice() const
        { return (getCost() * markup); }

        double getSalesTax() const
        { return (getCost() * taxRate); }

        double getTaxTotal() const
        { return (getCost() * taxRate) + getUnitPrice(); }

        double getSubTotal() const
        { return (getUnitPrice() + getCost()); }

        double getTotal() const
        { return (getSubTotal() + getSalesTax()); }

        int getQuantity() const
        { return quantity; }

        double recUnitPrice() const
        { return unitPrice; }

        double recSalesTax() const
        { return salesTax; }

        double recTaxTotal() const
        { return taxTotal; }

        double recSubTotal() const
        { return subTotal; }

        double recTotal() const
        { return total; }
};
#endif

InventoryItem.h


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

#ifndef INVENTORY_ITEM_H
#define INVENTORY_ITEM_H

#include <string>

class Inventory
{
    private:
        std::string description;        // The item name
              double    cost;                    // Cost of an item
              int       units;                // Number of units on hand
       
    public:
        Inventory()                            // Default constructor
        {
            description = " ";
            cost = 0.0;
            units = 0;
        }

        // Constructor accepting arguments for description, cost and units
        Inventory(std::string desc, double c, int u)
        {
            description = desc;
            cost = c;
            units = u;
        }

        void setDescription(std::string desc)
        { description = desc; }

        void setCost(double c)
        { cost = c; }

        void setUnits(int u)
        { units = u; }

        std::string getDescription() const
        { return description; }

        double getCost() const
        { return cost; }

        int getUnits()
        { return units; }
};
#endif

ShoppingBasket.h


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

#ifndef SHOPPING_BASKET_H
#define SHOPPING_BASKET_H

#include <string>

#include "InventoryItem.h"

class Basket
{
private:
    std::string description;        // Item description
    int numItems;                        // Number of items in the basket
    double cost;                        // Cost of items in the basket

public:
    Basket()                                // Default constructor
    {
        description = " ";
        numItems = 0;
        cost = 0.0;
    }

    Basket(int iQty)
    {
        numItems = iQty;
    }

    // Assigns values to description and cost
    void setItemInfo(const Inventory item)
    {
        description  = item.getDescription();
        cost         = item.getCost();
    }

    void setNumItems(int iQty)
    { numItems += iQty; }

    int getQuantity() const
    { return numItems; }

    std::string getDescription() const
    { return description; }

    double getCost() const
    { return cost; }
};
#endif

CashRegister.cpp


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

#include <iomanip>
#include <iostream>
#include <string>

#include "CashRegister.h"

/* **********************************************************
    CashRegister::isQuantity() accepts an Inventory object and
    an integer
    This function determines whether the value passed to it is
    valid. If it is, the value is assigned to the quantity
    member, and true is returned. If the number of available
    units is 0, the quantity member is assigned 0, a message
    is output to screen, and true is returned. If a quantity
    is entered that is greater than the number of available
    items, the item name and available quantity is output to
    screen, and false is returned.
   ********************************************************** */

bool CashRegister::isQuantity(Inventory item, int iQty)
{
    if (item.getUnits() > 0 && iQty <= item.getUnits())
    {
        quantity = iQty;
        return true;
    }
    else if (item.getUnits() == 0)
    {
        quantity = 0;
        std::cout << "\n" << item.getDescription() << " Out Of Stock\n";
        return true;
    }
    else
    {
        std::cout << "\nItem: " << item.getDescription() << "\n";
        std::cout << "Availabe quantity: " << item.getUnits() << "\n";
        return false;
    }

    return false;
}

/* **********************************************************
            CashRegister::setCost() accepts an Inventory object
    This function sets the cost for an item. The value to be
    assigned to the cost member is passed to it by the item
    object.
   ********************************************************** */

void CashRegister::setCost(const Inventory item)
{
    cost = item.getCost();
}

/* **********************************************************
    CashRegister::updateUnits() accepts a reference to an
    Inventory object
    This function sets the number of units on hand, stored in
    the item object member. The new value is calculated by
    subtracting the quantity of items bought from the units on
    hand stored in the item object.
   ********************************************************** */

void CashRegister::updateUnits(Inventory &item)
{
    item.setUnits(item.getUnits() - getQuantity());
}

/* **********************************************************
    CashRegister::updateRegister()
    This function keeps a running total of taxes and prices,
    while items are added to the basket. All values are
    multiplied by the quantity being purchased.
   ********************************************************** */

void CashRegister::updateRegister()
{
    unitPrice += getUnitPrice() * getQuantity();
    salesTax  += getSalesTax()  * getQuantity();
    subTotal  += getSubTotal()  * getQuantity();
    taxTotal  += getTaxTotal()  * getQuantity();
    total     += getTotal()     * getQuantity();
}

/* **********************************************************
   CashRegister::displayReceipt()
    This function outputs to screen the unit price, sales tax,
    tax-total, subtotal and total purchase price.
   ********************************************************** */

void CashRegister::displayReceipt()
{
    std::cout << std::fixed << std::showpoint << std::setprecision(2);

    std::cout << std::left << "Markup " << std::setw(26)
               << std::right << "$ "        << std::setw(6)
                 << recUnitPrice() << "\n";

    std::cout << std::left << "Sales-Tax " << std::setw(23)
                 << std::right << "$ " << std::setw(6)
                 << recSalesTax() << "\n";

    std::cout << std::left << "Tax-Total " << std::setw(23)
                 << std::right << "$ " << std::setw(6)
                 << recTaxTotal() << "\n\n";

    std::cout << std::left << "Sub-Total " << std::setw(23)
                 << std::right << "$ " << std::setw(6)
                 << recSubTotal() << "\n";

    std::cout << std::left << "Purchase Price " << std::setw(18)
                 << std::right << "$ " << std::setw(6)
                 << recTotal() << "\n";

    std::cout << "\nTHE BINFORD ITEM EMPORIUM \n"
               << "\t  THANKS YOU FOR YOUR PATRONAGE";
}

CashRegisterDm.cpp


/* CashRegisterDm.cpp - This program demonstrates the CashRegister class */

#include <iomanip>
#include <iostream>
#include <string>
#include <array>

#include "ShoppingBasket.h"
#include "CashRegister.h"
#include "InventoryItem.h"

const int NUM_ITEMS = 6;

void displayItems(std::array<Inventory, NUM_ITEMS>);
void shoppingBasket(std::array<Inventory, NUM_ITEMS> &,
                          std::array <Basket, NUM_ITEMS> &, CashRegister &);
void displayBasket(const std::array <Basket, NUM_ITEMS>);

int main()
{
    CashRegister sales;

    std::array<Inventory, NUM_ITEMS> items { Inventory("Hammer", 2.95, 3),
                                                          Inventory("Chisel", 3.75, 3),
                                                          Inventory("Wrench", 5.25, 3),
                                                          Inventory("Pliers", 6.95, 3),
                                                          Inventory("Crimper", 24.97, 13),
                                                          Inventory("Jab Saw", 7.97, 51) };
   
    std::array <Basket, NUM_ITEMS> content{ };

    char repeat = ' ';

    std::cout << "\tWELCOME TO THE BINFORD ITEM EMPORIUM\n\n";

    do
    {
        shoppingBasket(items, content, sales);

        std::cout << "\nDo you wish to buy another item? ";
        std::cin >> repeat;
        std::cout << "\n";

        while (toupper(repeat) != 'Y' && toupper(repeat) != 'N')
        {
            std::cout << "\nDo you wish to buy another item? ";
            std::cin >> repeat;
        }

        if (toupper(repeat) == 'N')
        {
            std::cout << "     BINFORD ITEM EMPORIUM INVOICE\n\n";

            displayBasket(content);
            sales.displayReceipt();
           
        }
    } while (toupper(repeat) != 'N');

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

/* **********************************************************
    displayItems() accepts a pointer to an Inventory object
    This function displays the item names, units on hand and
    item cost.
    ********************************************************** */

void displayItems(std::array<Inventory, NUM_ITEMS> item)
{
    std::cout << std::fixed << std::showpoint << std::setprecision(2);
    std::cout << "Item ID\t\t" << "Description\t\t" << "On Hand\t\t" << "Cost\n\n";

    for (int i = 0; i < NUM_ITEMS; i++)
    {
        if (item[i].getUnits() > 0)
        {
            std::cout << (i + 1) << "\t\t"
                       << item[i].getDescription() << "\t\t\t"
                         << item[i].getUnits() << "\t\t"
                         << item[i].getCost() << "\n";
        }
        else
        {
            std::cout << (i + 1) << "\t\t"
                       << item[i].getDescription() << "\t\t\t"
                         << "Out of stock\t"
                         << item[i].getCost() << "\n";
        }
    }
}

/* **********************************************************
   shoppingBasket() accepts a reference to an array of item
    objects, a reference parameter to an array of
    basket objects and a reference to a sales object
   
    The customer is asked to enter the item ID and quantity he
    or she wishes to buy. This information is then processed
    by member functions of the sales and basket classes.
   ********************************************************** */

void shoppingBasket(std::array<Inventory, NUM_ITEMS> &item, std::array <Basket, NUM_ITEMS> &basket,
                          CashRegister &sales)
{
    int iQty = 0;
    int iID = 0;

    displayItems(item);

    std::cout << "\nWhich item do you wish to buy? ";
    std::cin >> iID;

    while (iID <= 0 || iID > NUM_ITEMS)
    {
        std::cout << "\nWhich item do you wish to buy? (1 through " << NUM_ITEMS << ") ";
        std::cin >> iID;
    }

    std::cout << "How many items do you wish to buy? ";
    std::cin >> iQty;

    while (sales.isQuantity(item[iID - 1], iQty) == false)
    {
        std::cout << "How many items do you wish to buy? ";
        std::cin >> iQty;
    }   

    sales.setCost(item[iID-1]);
    sales.updateUnits(item[iID - 1]);
    sales.updateRegister();

    basket[iID - 1].setItemInfo(item[iID-1]);
    basket[iID - 1].setNumItems(sales.getQuantity());
}

/* **********************************************************
   displayBasket() accepts an array of basket objects
    This function outputs to screen the item name, quantity
    and cost of the items currently in the basket.
   ********************************************************** */

void displayBasket(const std::array <Basket, NUM_ITEMS> content)
{
    std::cout << std::fixed << std::showpoint << std::setprecision(2);

    for (int i = 0; i < NUM_ITEMS; i++)
    {
        if (content[i].getQuantity() > 0)
        {
            std::cout << "ITEM NAME: " << std::setw(28) << content[i].getDescription() << "\n"
                         << "QUANTITY:  " << std::setw(28) << content[i].getQuantity() << "\n"
                         << "COST: "        << std::setw(26)
                         << "$"               << std::setw(7) << content[i].getCost() << "\n\n";
        }   
    }
    std::cout << "---------------------------------------\n\n";
}

Example Output:





Tuesday, September 26, 2017

Programming Challenge 13.16 - Freezing and Boiling Points

Example Files: FreezingAndBoilingPoints.h
                          FreezingAndBoilingPoints.cpp
                          FreezingAndBoilingPointsDm.cpp

FreezingAndBoilingPoints.h


#ifndef FREEZING_AND_BOILING_POINTS_H
#define FREEZING_AND_BOILING_POINTS_H

class Chemistry
{
    private:
        int temperature;        // Holds a single temperature

    public:
        Chemistry()
        {
            temperature = 0;
        }

        Chemistry(int temp)
        {
            temperature = temp;
        }

        bool isEthylFreezing();
        bool isEthylBoiling();
        bool isOxygenFreezing();
        bool isOxygenBoiling();
        bool isWaterFreezing();
        bool isWaterBoiling();

        int getTemperature() const
        { return temperature; }
};
#endif

FreezingAndBoilingPoints.cpp


/* FreezingAndBoilingPoints.cpp Implementation file for the Chemistry class. */

#include "FreezingAndBoilingPoints.h"

enum Freezing { ETHYL_FR = -173, OXYGEN_FR = -362, WATER_FR = 32 };
enum Boiling { ETHYL_BO = 172, OXYGEN_BO = -306, WATER_BO = 212 };

/* **********************************************************
            Chemistry::isEthylFreezing()
   If Ethyl is freezing at a certain temperature, true is
    returned from this function, else false is returned.
   ********************************************************** */

bool Chemistry::isEthylFreezing()
{
    if (getTemperature() <= ETHYL_FR)
    { return true; }

    return false;
}

/* **********************************************************
            Chemistry::isOxygenFreezing()
   If Oxygen is freezing at a certain temperature, true is
    returned from this function, else false is returned.
   ********************************************************** */

bool Chemistry::isOxygenFreezing()
{
    if (getTemperature() <= OXYGEN_FR)
    { return true; }

    return false;
}

/* **********************************************************
            Chemistry::isWaterFreezing()
   If Water is freezing at a certain temperature, true is
    returned from this function, else false is returned.
   ********************************************************** */

bool Chemistry::isWaterFreezing()
{
    if (getTemperature() <= WATER_FR)
    { return true; }

    return false;
}

/* **********************************************************
            Chemistry::isEthylFreezing()
   If Ethyl is freezing at a certain temperature, true is
    returned from this function, else false is returned.
   ********************************************************** */

bool Chemistry::isEthylBoiling()
{
    if (getTemperature() >= ETHYL_BO)
    { return true; }

    return false;
}

/* **********************************************************
            Chemistry::isOxygenBoiling()
   If Oxygen is boiling at a certain temperature, true is
    returned from this function, else false is returned.
   ********************************************************** */

bool Chemistry::isOxygenBoiling()
{
    if (getTemperature() >= OXYGEN_BO)
    { return true; }

    return false;
}

/* **********************************************************
            Chemistry::isWaterBoiling()
   If Water is boiling at a certain temperature, true is
    returned from this function, else false is returned.
   ********************************************************** */

bool Chemistry::isWaterBoiling()
{
    if (getTemperature() >= WATER_BO)
    { return true; }

    return false;
}


FreezingAndBoilingPointsDm.cpp


/* FreezingAndBoilingPointsDm.cpp - Demo file for the Chemistry class. */

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

using std::string;
using std::cin;
using std::cout;

void isFreezing(Chemistry);
void isBoiling(Chemistry);

int main()
{
    char again = ' ';
    int temperature = 0;

    cout << "FREEZING AND BOILING POINTS\n\n"
         << "Enter a temperature in Fahrenheit, and I will tell you which substances\n"
          << "are freezing and which are boiling at that temperature.\n\n";

    do
    {
        cout << "Enter a temperature: ";
        cin >> temperature;

        Chemistry temp(temperature);

        isFreezing(temp);
        isBoiling(temp);

        cout << "\nDo you wish to try this again (Y/N)? ";
        cin >> again;
        cout << "\n";

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

        if (toupper(again) == 'N')
        {
            cout << "Have a nice day!";
        }
    } while (toupper(again) != 'N');

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

/* **********************************************************
    isFreezing() accepts a Chemistry object as its argument
   This function outputs each substance that is freezing at a
    certain temperature to screen.
   ********************************************************** */

void isFreezing(Chemistry temp)
{
    cout << "\nThese substances freeze at " << temp.getTemperature() << " degrees F:\n";

    if (temp.isEthylFreezing())
    {
        cout << "\nEthyl";
    }

    if (temp.isOxygenFreezing())
    {
        cout << "\nOxygen";
    }

    if (temp.isWaterFreezing())
    {
        cout << "\nWater";
    }
}

/* **********************************************************
    isBoiling() accepts a Chemistry object as its argument
   This function outputs each substance that is boiling at a
    certain temperature to screen.
   ********************************************************** */

void isBoiling(Chemistry temp)
{
    cout << "\nThese substances boil at " << temp.getTemperature() << " degrees F:\n\n";

    if (temp.isEthylBoiling())
    {
        cout << "Ethyl\n";
    }

    if (temp.isOxygenBoiling())
    {
        cout << "Oxygen\n";
    }

    if (temp.isWaterBoiling())
    {
        cout << "Water\n";
    }
}

Example Output:




Sunday, September 24, 2017

Programming Challenge 13.15 - Mortgage Payment

Example Files: MortgagePayment.h
                          MortgagePayment.cpp
                          MortgagePaymentDm.cpp

MortgagePayment.h


#ifndef MORTGAGE_PAYMENT_H
#define MORTGAGE_PAYMENT_H

class Mortgage
{
    private:
        double loanAmnt;                    // The loan amount
        double monthlyPayment;            // The monthly payment
        double interestRate;                // The annual interest rate
        int    terms;                        // Number of years

    public:
    Mortgage() : loanAmnt(0.0), monthlyPayment(0.0), interestRate(0.0), terms(0)
    { }

        bool setAmount(double);           
        bool setRate(double);
        bool setTerm(int);
        void calcPayment();

        double getAmount() const
        { return loanAmnt; }

        double getRate() const
        { return interestRate; }

        int getTerms() const
        { return terms; }

        double getPayment() const
        { return monthlyPayment; }
};
#endif

MortgagePayment.cpp


/* MortgagePaymentDm.cpp - Implementation file for the Mortgage Payment class. */

#include <math.h>
#include "MorgagePayment.h"

/* **********************************************************
            Mortgage::setAmount() accepts a double as argument
    This function sets the total loan amount, and assigns this
    value to the loanAmnt member.
   ********************************************************** */

bool Mortgage::setAmount(double amnt)
{
    if (amnt > 0)
    {
        loanAmnt = amnt;
        return true;
    }

    return false;
}

/* **********************************************************
            Mortgage::setRate() accepts a double as argument
    This function sets the interest rate, and assigns the
    value passed to it to the interestRate member.
   ********************************************************** */

bool Mortgage::setRate(double iRate)
{
    if (iRate > 0.0 && iRate <= 50.0)
    {
        interestRate = iRate;
        return true;
    }

    return false;
}

/* **********************************************************
            Mortgage::setTerm() accepts an int as argument
    This function sets the term in years, and assigns the
    value passed to it to the terms member.
   ********************************************************** */

bool Mortgage::setTerm(int t)
{
    if (t > 0 && t <= 40)
    {
        terms = t;
        return true;
    }

    return false;
}

/* **********************************************************
            Mortgage::calcPayment()
    This function calculates the monthly payments and assigns
    the result to the monthlyPayment member.
   ********************************************************** */

void Mortgage::calcPayment()
{
    int    mTerms = (getTerms() * 12);
    double iRate = (getRate() / 100) / 12;

    monthlyPayment = getAmount() * (pow(iRate + 1, mTerms)) *
                      iRate / (pow(iRate + 1, mTerms) - 1);
}

MortgagePaymentDm.cpp


/* MortgagePaymentDm.cpp - Demonstration file for the Mortgage Payment class. */

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

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

void introduction();
void getData(Mortgage &);
void displayData(const Mortgage);

int main()
{
    Mortgage monthlyPayment;

    introduction();

    getData(monthlyPayment);

    monthlyPayment.calcPayment();
    displayData(monthlyPayment);

    cout << "\n\n\tThe ASHIKAGA BANK Team wishes you a successful day\n"
          << "\tand thanks you for your patronage!";

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

/* **********************************************************
    introduction()
    This function introduces the basic features to the user.
   ********************************************************** */

void introduction()
{
    cout << "\t\tASHIKAGA BANK - MORTGAGE PAYMENT CALCULATOR\n\n";
    cout << "\tDear Customer, this application allows you to calculate the monthly\n"
          << "\tamount of money you will have to pay on your home mortgage. You are\n"
          << "\tasked to enter the Loan Amount (Ex: 500,000), the Interest Rate in\n"
          << "\t(Ex: 5.50), and the term in years (Ex: 30).\n\n"
          << "\tThe ASHIKAGA BANK hopes that this new service will benefit our valued\n"
          << "\tcustomers. We thank you for your continued patronage and interest.\n\n"
          << "\tYour ASHIKAGA BANK Team.\n\n";
}

/* **********************************************************
    getData() accepts a reference to a monthlyPayment object.
    This function asks the user to input the number of terms
    in years, the loan amount and the annual interest rate.
   ********************************************************** */

void getData(Mortgage &monthlyPayment)
{
    int    terms = 0;
    double amount = 0.0;
    double iRate = 0.0;

    cout << "\t\tASHIKAGA BANK - MORTGAGE PAYMENT - CUSTOMER FINANCIAL DATA\n\n";
    cout << "\tDear Customer,\n\n"
          << "\tPlease be utmost careful when entering the information asked of you\n"
          << "\tin the following three step process, else we cannot guarantee for the\n"
          << "\tcorrectness of the results. We must also warn you that we are not legally\n"
          << "\tliable for any financial damage that may occur.\n\n";

    cout << "\tStep 1:\n"
         << "\tLoan amount: $ ";
    cin >> amount;

    while (monthlyPayment.setAmount(amount) == false)
    {
        cout << "\n\tStep 1:\n"
             << "\tLoan amount: $ ";
        cin >> amount;
    }

    cout << "\n\tStep 2:\n"
        << "\tAnnual interest rate: % ";
    cin >> iRate;

    while (monthlyPayment.setRate(iRate) == false)
    {
        cout << "\n\tStep 2:\n"
              << "\tAnnual interest rate: % ";
        cin >> iRate;
    }

    cout << "\n\tStep 3:\n"
          << "\tNumber of terms in years: ";
    cin >> terms;

    while (monthlyPayment.setTerm(terms) == false)
    {
        cout << "\n\tStep 3:\n"
              << "\tNumber of terms in years: ";
        cin >> terms;
    }

    cout << "\n\tThank you! Your data will now be processed ...\n\n";
}

/* **********************************************************
   displayData() accepts a const monthlyPayment object
    This function outputs a detailed report, telling the user
    how high his or her monthly mortgage burden will be.
   ********************************************************** */

void displayData(const Mortgage monthlyPayment)
{
    cout << std::setprecision(2) << std::fixed << std::showpoint;
    cout << "\t\tASHIKAGA BANK - MONTHLY MORTGAGE PAYMENT PLAN\n\n";
    cout << "\tDear Customer,\n\n"
          << "\tAccording to the following data you kindly provided:\n\n"
          << "\tLoan Amount" << std::setw(25) << "$ " << monthlyPayment.getAmount() << "\n"
          << "\tYearly Interest Rate"
          << std::setw(15) << "%" << std::setw(10) << monthlyPayment.getRate() << "\n"
          << "\tLoan Term: " << std::setw(28) << monthlyPayment.getTerms() << " Years\n\n"
          << "\tOur calculation indicates that your monthly payment burden will be $ "
          << monthlyPayment.getPayment();
}

Example Output: 




Saturday, September 23, 2017

No Advertisements Please





This post only concerns those among my visitors who happen to think that the comment section of this humble blog is a playground for advertisements. Let me tell you, it is not. If you would like to have your page or service advertised, please ask me. I will consider adding a banner to your website or blog under the following conditions:

A) It is a legit website or blog, which my visitors can safely visit and might benefit from the content you offer.

B) It must not contain content considered harmful to youth, children, or young adults, it most not contain anything racist, or something that hurts the religious feeling of any of my visitors, nor must it contain something that is generally considered a no-go.

My wish is to provide all visitors a pleasant browsing experience, undisturbed by advertisments all over the place, not even in comments. My wish is not to earn money on my visitors, which is the reason why I keep this blog ad-free. 

With this I wish all my visitors a very pleasant weekend, and those visitors it concerns I ask to respect the rules. As for me, it is back to writing more classes, which, even though a challenge, I already come to like working with very much. 

Programming Challenge 13.14 - Fishing Game Simulation

Example Files: ClearsSreen.h
                          FishingGameSimulation.h
                          FishingGameSimulation.cpp
                          FishingGameSimulationDm.cpp


FishingGameSimulation.h


#ifndef FISHING_GAME_SIMULATION_H
#define FISHING_GAME_SIMULATION_H

#include <array>

class Fish
{
    private:
        static constexpr int NUM_PRIZES = 7;        // The number of prizes a player can win
        static constexpr int NUM_ITEMS = 6;            // The number of items to be caught
        static constexpr int DIE_SIDES = 6;            // The number of sides of the die

       static const std::array<std::string, NUM_PRIZES> prizes;                // Holds the prize names
        static const std::array<std::string, NUM_ITEMS> items;               // Holds the items being caught
        static const std::array<int, NUM_ITEMS> scoreList;                        // Holds a score list
        static const std::array <int, Fish::NUM_PRIZES> highScoreList;        // Holds a list of highscores

        int             sides;                     // Number of sides of the die
        int             value;                    // The die's value
        int             score;                    // Holds the score achieved by a player
        std::string itemName;            // Holds the items a player must catch
        std::string prizeName;           // Holds the name of prizes a player can win

    public:
        Fish() : sides(DIE_SIDES), value(0), score(0), itemName(" "), prizeName(" ")
        {
            initRNG();
        }

        void initRNG();
        void roll();
        void setItemName();
        void setScore();
        void prizeList();

        int getNumPrizes() const                     // Returns the number of prizes
        { return NUM_PRIZES; }

        int getNumItems() const                      // Returns the number of items
        { return NUM_ITEMS; }

        int getSides() const                              // Returns the number of sides of a die
        { return sides; }

        int getValue() const                              // Returns the die value
        { return value; }

        std::string getItem() const                    // Returns the item name
        { return itemName; }

        int getScore() const                              // Returns the score achieved by a player
        { return score; }

        std::string getPrizeName() const          // Returns the name of a prize
        { return prizeName; }

        int getScoreList(int i) const                  // Returns a value contained in the scoreList array
        { return scoreList[i]; }

        std::string getPrizeList(int i) const       // Returns a price contained in the prizes array
        { return prizes[i]; }

        std::string getItemList(int i) const        // Returns an item from the items array
        { return items[i]; }
   
        int getHighScore(int i) const                // Returns a value from the highScoreList array
        { return highScoreList[i]; }
};
#endif

FishingGameSimulation.cpp


/* FishingGameSimulation.cpp - Implementation file for the Fish class. */

#include <array>
#include <cstdlib>
#include <ctime>
#include <string>
#include "FishingGameSimulation.h"

const std::array <int, Fish::NUM_ITEMS> Fish::scoreList         { 1, 5, 10, 15, 20, 25 };
const std::array <int, Fish::NUM_PRIZES> Fish::highScoreList { 5, 50, 75, 100, 250, 400, 1000 };

const std::array <std::string, Fish::NUM_ITEMS> Fish::items
{
    "Horseshoe", "Red Catfish", "Black Bass", "Spearfish",
    "Rainbow Trout", "Item Chest"
};

const std::array <std::string, Fish::NUM_PRIZES> Fish::prizes
{
    "Chocolate Bar", "Teru Teru Bozu Doll", "Ramen Super Pack",
    "Miyuki Figurine", "BD-Player Set", "Rome Crossrocket Snowboard",
    "Kimono"
};

/* **********************************************************
            Fish::initRNG()
    This function initializes the RNG.
   ********************************************************** */

void Fish::initRNG()
{
    time_t seed = time(0);

    srand(static_cast<unsigned int>(seed));

    roll();
}

/* **********************************************************
            Fish::roll()

    This function simulates a die-roll. It generates a random
    number, which is copied to the value member variable.
   ********************************************************** */

void Fish::roll()
{
    const int MIN_VALUE = 1;

    value = (rand() % (getSides() - MIN_VALUE + 1)) + MIN_VALUE;

    setItemName();
}

/* **********************************************************
            Fish::setItemName()
    This function sets the itemName variable.
   ********************************************************** */

void Fish::setItemName()
{
    itemName = items[getValue() - 1];
}

/* **********************************************************
            Fish::setScore()
    This function sets and updates the score member variable
    during gameplay.
   ********************************************************** */

void Fish::setScore()
{
    score += scoreList[getValue() - 1];

    prizeList();
}

/* **********************************************************
            Fish::prizeList()
    This function determines the prize a player will receive.
    The getScore() function is called, and compared against
    the highScore array. If the score is equal to or higher
    than one of the highscores, the prizeName member gets the
    prize names from the prize array. The getPrizeList(int)
    function contains a call to the array.
   ********************************************************** */

void Fish::prizeList()
{
    for (int i = 0; i < NUM_PRIZES; i++)
    {
        getScore() >= getHighScore(i) ? prizeName = getPrizeList(i) : prizeName;
    }
}

FishingGameSimulationDm.cpp


/* FishingGameSimulationDm.cpp - Demonstration file for the Fish class. */

#include <iomanip>
#include <iostream>
#include <string>
#include "FishingGameSimulation.h"
#include "ClearScreen.h"

enum Menu_Items { DISPLAY_PRIZES = 'D', START_GAME = 'S', QUIT = 'Q' };

void menu();
char options();
void gameLoop(Fish &);
void displayPrizeList(const Fish);
void displayItemList(const Fish);
void displayScore(Fish);

int main()
{
    menu();

    return 0;
}

/* **********************************************************
    options()
    This function contains the menu options. The player is
    asked to make a choice, which is validated and, if it is
    valid, is returned.
    ********************************************************** */

char options()
{
    char choice = ' ';

    std::cout << "\t\tFISHING GAME SIMULATION\n\n"
               << "\t[D]ISPLAY PRIZES\n"
               << "\t[S]TART GAME\n"
                 << "\t[Q]UIT\n\n"
               << "\tSelect: ";
    std::cin >> choice;

    while (toupper(choice) < DISPLAY_PRIZES && toupper(choice) > QUIT)
    {
        std::cout << "\nSelect: ";
        std::cin >> choice;
    }

    std::cout << "\n";
    return (toupper(choice));
}

/* **********************************************************
    menu()
    This function represents the main menu of the game. The
    player can either start a new game or quit.
   ********************************************************** */

void menu()
{
    Fish fishing;

    char choice = ' ';

    do
    {
        choice = options();

        switch (choice)
        {
            case DISPLAY_PRIZES:
            {
                clearScreen();
                displayPrizeList(fishing);
                clearScreen();
            } break;

            case START_GAME:
            {
                clearScreen();
                gameLoop(fishing);
                clearScreen();
            } break;

            case QUIT:
            {
                if (fishing.getScore() != 0)
                {
                    std::cout << "Congratulations, you earned " << fishing.getScore() << " points!\n"
                               << "You win a " << fishing.getPrizeName() << "!";
                    std::cin.get();
                    std::cin.ignore();
                }
                else
                {
                    std::cout << "ONLY THOSE WHO PLAY WIN!";
                    std::cin.get();
                    std::cin.ignore();
                }
            } break;
        }
    } while (toupper(choice) != QUIT);
}

/* **********************************************************
    displayItemList() accepts a fish object
    This function displays the items a player must catch and
    their point values.
   ********************************************************** */

void displayItemList(const Fish fishing)
{
    std::cout << "\t\tFISHING GAME SIMULATION\n\n";
    std::cout << "ITEM NAME " << std::setw(40) << "ITEM VALUE\n"
               << std::setfill('*') << std::setw(51) << "\n"
               << std::setfill(' ');

    for (int i = 0; i < fishing.getNumItems(); i++)
    {
        std::cout << std::setw(45) << std::left << fishing.getItemList(i)
                   << std::setw(5) << std::right << fishing.getScoreList(i) << "\n";
    }
}

/* **********************************************************
    displayPrizeList()
    This function displays a list of prizes a player can win,
    and the score needed to win it.
   ********************************************************** */

void displayPrizeList(const Fish fishing)
{
    std::cout << "\t\tFISHING GAME SIMULATON\n\n";
    std::cout << "PRIZE LIST " << std::setw(40) << "SCORE NEEDED\n"
              << std::setfill('*') <<std::setw(51) << "\n"
              << std::setfill(' ');

    for (int i = 0; i < fishing.getNumPrizes(); i++)
    {
        std::cout << std::setw(45) << std::left << fishing.getPrizeList(i)
                     << std::setw(5) << std::right << fishing.getHighScore(i) << "\n";
    }

    std::cout << "\nPress a key to return to the menu ...";
    std::cin.get();
    std::cin.ignore();
}

/* **********************************************************
    gameLoop()
    In this function the game is executed, and the score is
    accumulated for as long as the player decides that he or
    she wishes to continue playing.
   ********************************************************** */

void gameLoop(Fish &fishing)
{
    char again = ' ';

    displayItemList(fishing);

    do
    {
        fishing.roll();

        std::cout << "\nCaught Item: " << fishing.getItem() << "\n";

        fishing.setScore();

        std::cout << "Continue [Y/N]? ";
        std::cin >> again;

        if (toupper(again) == 'Y')
        {       
            clearScreen();
            displayItemList(fishing);
        }

        while (toupper(again) != 'Y' && toupper(again) != 'N')
        {
            std::cout << "Play Again? (Y/N) ";
            std::cin >> again;
        }
    } while (toupper(again) != 'N');
   
    std::cout << "\n";
}

Example Output:







Wednesday, September 20, 2017

Programming Challenge 13.13 - Tossing Coins for a Dollar

Example Files: ClearScreen.h
                         CoinTossSimulator.h
                         TossingCoinsForADollar.cpp
                         TossingCoinsForADollarDm.cpp

CoinTossSimulator.h


/* CoinTossSimulator.h - Specification file for the Coin class. */

#ifndef COIN_TOSS_SIMULATOR_H
#define COIN_TOSS_SIMULATOR_H

#include <string>

class Coin
{
    private:
        std::string sideUp;                    // The side of the coin facing up
        int            numWins;                 // Holds the accrued number of wins
        int            numLosses;              // Holds the accrued number of losses
        int            balance;                    // Holds the balance
       
    public:
        Coin::Coin() : balance(0), numWins(0), numLosses(0)        // Constructor
        {
            initRNG();
        }

        void initRNG();                        // Initializes the random number generator
        void toss();                                // Performs a coin-toss
        void setBalance(int);                // Adds coin values to the balance member
        void setScore();                        // Sets the current score

        std::string getSideUp() const      // Returns the side of the coin facing up
        { return sideUp; }

        int getNumWins() const              // Returns the number of wins
        { return numWins; }

        int getNumLosses() const            // Returns the number of losses
        { return numLosses; }

        int getBalance() const                  // Returns the current balance
        { return balance; }
};
#endif

TossingCoinsForADollar.cpp


/* CoinTossSimulator.cpp - Implementation file for the Coin class. */

#include <cstdlib>
#include <ctime>
#include "CointTossSimulator.h"

/* **********************************************************
            Coin::initRNG()
    This function initializes the RNG.
   ********************************************************** */

void Coin::initRNG()
{
    srand((unsigned int)time(0));
}

/* **********************************************************
            Coin::toss()
    This function determines the coin side facing up after
    each toss. The side facing up is assigned to the sideUp
    member variable.
   ********************************************************** */

void Coin::toss()
{
    const int HEADS = 1;
    const int TAILS = 2;

    unsigned int sides = 0;

    sides = HEADS + rand() % TAILS;

    if (sides == HEADS)
    {
        sideUp = "Heads";
    }
    else
    {
        sideUp = "Tails";
    }   
}

/* **********************************************************
            Coin::setBalance() accepts an integer value
    This function adds the coin values passed to it to the
    balance member.
   ********************************************************** */

void Coin::setBalance(int coinValue)
{
    balance += coinValue;
}

/* **********************************************************
            Coin::setScore()
    The ternary determines the current balance. If it is 100,
    numWins increases by 1, else numLosses increases, and the
    balance is reset to 0.
   ********************************************************** */

void Coin::setScore()
{
    getBalance() == 100 ? numWins += 1 : numLosses += 1;   
    balance = 0;
}

TossingCoinsForADollarDm.cpp


/* TossingCoinsForADollarDm.cpp - This program demonstrates the Coin class. */

#include <iomanip>
#include <iostream>
#include <string>
#include "CointTossSimulator.h"
#include "ClearScreen.h"

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

enum CoinValues { NICKEL = 5, DIME = 10, QUARTER = 25 };
enum MenuItems { INTRO = 'I', DISPLAY_SCORE = 'D', PLAY = 'P', QUIT = 'Q' };

void intro();
char options();
void menu(Coin &, Coin &, Coin &, Coin &);
void game(Coin &, Coin &, Coin &, Coin &);
void quit(const Coin);

int main()
{
    Coin coinToss;
    Coin nickel;
    Coin dime;
    Coin quarter;

    menu(coinToss, nickel, dime, quarter);

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

/* **********************************************************
    intro()
    This function welcomes the player and introduces him or
    her to the game.
   ********************************************************** */

void intro()
{
    cout << "\t\tTOSSING COINS FOR A DOLLAR GAME\n\n"
          << "Hello, friend! *Psst!* Yes, you, come closer! Closer! How about a little game?\n"
          << "Win a dollar each round, the odds are most fair! A nickel, a dime and a quarter\n"
          << "we toss, their faces we add, the tails we'll forget. The sum of a dollar, the goal\n"
          << "is set, play a couple of rounds, and your fortune is made!\n\n";
}

/* **********************************************************
    options()
    This function contains the menu options. The player is
    asked to make a choice, which is validated, and - if valid
    is returned.
   ********************************************************** */

char options()
{
    char choice = ' ';

    cout << "\t\tTOSSING COINS FOR A DOLLAR GAME\n\n"
          << "\t[I]ntro\n"
          << "\t[P]lay\n"
          << "\t[D]isplay Score\n"
          << "\t[Q]uit\n\n"
          << "\tSelect: ";
    cin >> choice;

    while (toupper(choice) < INTRO && toupper(choice) > QUIT)
    {
        cout << "\nSelect: ";
        cin >> choice;
    }

    return (toupper(choice));
}

/* **********************************************************
    menu() accepts four Coin objects passed to it by reference
    This function acts as menu.
   ********************************************************** */

void menu(Coin &coinToss, Coin &nickel, Coin &dime, Coin &quarter)
{   
    char choice = ' ';

    do
    {
        choice = options();
        cout << "\n";
   
        switch (choice)
        {
           
            case INTRO:
            {
                clearScreen();
                intro();
               
            } break;

            case PLAY:
            {
                game(coinToss, nickel, dime, quarter);   
               
                cout << "Press Enter to Continue ...";
                cin.get();
                cin.ignore();
               
                clearScreen();
            } break;

            case DISPLAY_SCORE:
            {
                cout << "Won:  $" << std::setw(4) << coinToss.getNumWins() << "\n";
                cout << "Lost: $" << std::setw(4) << coinToss.getNumLosses() << "\n";
               
                cout << "Press Enter to Continue ...";
                cin.get();
                cin.ignore();
               
                clearScreen();
            } break;

            case QUIT:
            {
                quit(coinToss);
            }
        }
    } while (toupper(choice) != 'Q');
}

/* **********************************************************
    game() accepts four Coin objects passed to it by reference
    This function tosses the three coins as long as the score
    is lower than or equal to 100. After each toss, the sides
    currently facing up are output to screen, and the balance
    as well as the score is set.
   ********************************************************** */

void game(Coin &coinToss, Coin &nickel, Coin &dime, Coin &quarter)
{
    const int GOAL_SCORE = 100;

    do
    {
        nickel.toss();
        nickel.getSideUp() == "Heads" ? coinToss.setBalance(NICKEL) : 0;

        dime.toss();
        dime.getSideUp() == "Heads" ? coinToss.setBalance(DIME) : 0;

        quarter.toss();
        quarter.getSideUp() == "Heads" ? coinToss.setBalance(QUARTER) : 0;

        // Display the side facing up after each toss
        cout << "Nickel: " << std::setw(11) << nickel.getSideUp() << "\n";
        cout << "Dime: " << std::setw(13) << dime.getSideUp() << "\n";
        cout << "Quarter: " << std::setw(10) << quarter.getSideUp() << "\n";

        cout << std::fixed << std::showpoint << std::setprecision(2);
        cout << "Balance: " << std::setw(4) << coinToss.getBalance() << " cents\n\n";

        if (coinToss.getBalance() == GOAL_SCORE)
        {
            cout << "$1.00 on the nickel and the dime? Incredible, "
                  << "but next round will be mine.\n";
            break;
        }
        else if (coinToss.getBalance() > GOAL_SCORE)
        {
            cout << "$" << (static_cast<double>(coinToss.getBalance()) / 100) << " cents "
                 << "this round is mine! Better luck next dime!\n";
        }
    } while (coinToss.getBalance() <= GOAL_SCORE);

    coinToss.setScore();   
}

/* **********************************************************
    quit() accepts a Coin object as argument
    If the player decides to quit the game, his or her final
    score is output to screen.
   ********************************************************** */

void quit(const Coin coinToss)
{
    cout << "QUITTERS, CHEATERS! But fine ... go ahead, go ... ";
    coinToss.getNumWins() > coinToss.getNumLosses() ?
               cout << "you are the winner, $"
                      << (coinToss.getNumWins() - coinToss.getNumLosses())
                      << " are now thine!" :
                cout << "\nbut before you leave, pay the $"
                      << (coinToss.getNumLosses() - coinToss.getNumWins())
                      << " you still owe!";
}

Example Output: