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:








Monday, September 18, 2017

Visual Studio Debugging Error and Solution

About a week ago I was working on a Programming Challenge. The debugger was running, and the only breakpoint was set on a string member variable. Hovering over the [allocator] section to see what was going, things changed dramatically. An error message?

_Ptr = 0x325785 <Error reading characters of string.>  

What is going on here? Have I done something wrong? Is it some problem with Visual Studio? Could it be a component of my security suite that is causing this error? Whatever it was, why was the program running and compiling and building just fine? Why was the output as expected? Why didn't the program freeze or crash if there is indeed an error?

My best bet seemed to be to look this error up on the Internet. To my surprise the results matching my search were sparse. Microsoft does seem to be aware that the error exists, but no bugfix or solution seems to exist for it. One of the few solutions I found didn't work either: "Disable all Optimizations in the project properties. (Alt + F7), C/C++, Optimizations and Linker, Optimizations." 


I was left to my own devices to solve the problem ... Starting up VS, setting up a new project, toying around with the project settings, trying a different framework, nothing helped. Next I was loading some of my old projects to see whether this problem occurs or doesn't and it did. Days went by without getting any closer to the root of the problem or finding a solution for it, I decided to wipe my system. With a clean installation of both the OS and VS my hope was that things would take a turn for the better. They did not ...

Back on square one I had two options:

One: Ignore it. Impossible ... 
Two: Trying my luck on finding a solution Online once more, ...

Before going Online, I set up another project in VS:

#include <string>
#include <iostream>

int main()

{
    std::string myLittlePonyOne = "Rarity";
    std::string myLittlePonyTwo = "Twilight Sparkle";

    std::cout << "My favorite My Little Pony Characters are:\n"
                  << myLittlePonyOne << " \n"
                  << myLittlePonyTwo << " \n";

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

I didn't debug it right away, else I would have discovered that this little program contains the solution to the problem. Had I done it without looking for a solution, I wouldn't have found the answer to the question why this error was occurring and what was causing it. Here is the 'solution' or rather answer to the problem.

The STL string classes contain an optimization called Small String Optimization or SSO for short. To learn more about it, please visit Giovanni Dicanio's C++ Corner on the Internet. Having read this blog-post, I immediately went back to the IDE, started the debugger, and found that this was the source of the 'error'. Consider the following screenshots:


As "Rarity" is very short, it is a small variable, so there is no memory allocated on the heap, resulting in this 'error' message. 


Not so in case of "Twilight Sparkle", which is long enough, resulting in correct behavior. 

After carrying out some more tests just to be sure I found that this was indeed the source of the 'error' that is anything but. "It's not a bug, it's a feature", or in this case "It's not a bug, it's an optimization", to coin a new phrase. I'm just glad that in the end it turned out that all of my programs old and new containing string class in the end turn out not to be error-ridden.  

I sincerely hope that none of my readers, much less my fellow learners, will have to go through so much trouble ... With this, I wish my readers and fellow learners a successful new week, and thank you very much for your visit and continued interest in this modest blog. As for me, it is time to write more code, and to overcome more errors and bugs.

Saturday, September 16, 2017

Programming Challenge 13.12 - Coin Toss Simulator

Example Files: CoinTossSimulator.h
                          CoinTossSimulator.cpp
                          CoinTossSimulatorDm.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             cntHeads;                 // Holds the count for heads
        int             cntTails;                   // Holds the count for tails

    public:
        Coin::Coin() : sideUp(""), cntHeads(0), cntTails(0)    // Constructor
        {
           initRNG();
           toss();
           sideCount();
        }

        void initRNG();                        // Initializes the random number generator
        void toss();                               // Performs a coin-toss
        void sideCount();                     // Counts the number of times heads or tails is facing up

        std::string getSideUp() const       
        { return sideUp; }

        int Coin::getCntHeads() const       
        { return cntHeads; }
       
        int Coin::getCntTails() const
        { return cntTails; }
};
#endif

CoinTossSimulator.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(NULL));
}

/* **********************************************************
            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::sideCount()
    This function uses a ternary operator to count the number
    of times 'heads' and 'tails' are facing up.
   ********************************************************** */

void Coin::sideCount()
{
    sideUp == "Heads" ? cntHeads++ : cntTails++;
}

CoinTossSimulatorDm.cpp


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

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

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

int main()
{
    Coin coinToss;
   
    const int NUM_TOSSES = 20;
   
    cout << "\t\tCOIN TOSS SIMULATOR\n\n";
    cout << "I will now perform an initial toss.\n\n";
    cout << "The side facing up is: " << coinToss.getSideUp() << "\n\n";
    cout << "I will now toss the coin " << NUM_TOSSES << " times.";

    cout << "\n(Press a key to continue)\n";
    cin.ignore();

    for (int i = 0; i < 20; i++)
    {
        coinToss.toss();
        coinToss.sideCount();

        cout << "Toss #" << std::setw(2)  << (i + 1) << ": "
                              << std::setw(18) << coinToss.getSideUp() << "\n";
    }

    cout << "\nThe number of times 'Heads' was facing up: " << coinToss.getCntHeads() << "\n";
    cout << "The number of times 'Tails' was facing up: "   << coinToss.getCntTails();
    cout << "\n\nThis program will now exit. Have a nice day!";
   
    cin.ignore();
    return 0;
}

Example Output:



Saturday, September 9, 2017

Programming Challenge 13.11 - Payroll

Example Files: Payroll.h
                          Payroll.cpp
                          PayrollDemo.cpp

Payroll.h


#ifndef PAYROLL_H
#define PAYROLL_H

class Payroll
{
    private:
        double payRate;        // The hourly pay rate
        float  hrsWorked;        // The hours worked by an employee
        double grossPay;        // The gross pay

    public:
        Payroll()                // Default constructor
        {
            payRate = 0.0;
            hrsWorked = 0.0;
            grossPay = 0.0;
        }

        void setHrsWorked(float hrs);               
        void setPayRate(double pRate);           
        void calcGrossPay();                           

        float getHoursWorked() const        // Returns the hours worked
        { return hrsWorked; }

        double getGrossPay() const            // Returns the gross pay
        { return grossPay; }
};
#endif


Payroll.cpp


/* Payroll.h - Implementation file for the Payroll class. */

#include <iostream>
#include "Payroll.h"

/* **********************************************************
            Payroll::setHrsWorked(accepts a float)
    This function sets the hours worked. If a value passed to
    is within range it is copied to the hrsWorked member. If
    the value for hours worked is too high, hrsWorked is set 
    to 60 hrs, else if the value is lower than or equal to 0,
    hrsWorked is set to 5.0.
   ********************************************************** */

void Payroll::setHrsWorked(float hrs)
{
    enum HoursWorked { MIN_HRS = 5, MAX_HRS = 60 };

    if (hrs >= MIN_HRS && hrs <= MAX_HRS)
    {
        hrsWorked = hrs;
    }
    else if (hrs > MAX_HRS)
    {
        std::cout << "\nValue for hours worked too high.\n"
                   << "Setting default value: " << MAX_HRS << "hrs.\n\n";
        hrsWorked = MAX_HRS;
    }
    else if (hrs <= MIN_HRS)
    { std::cout << "\nValue for hours worked too low.\n"
                << "Setting default value: " << MIN_HRS << " hrs.\n\n";
        hrsWorked = MIN_HRS;
    }
}

/* **********************************************************
            Payroll::setPayRate(accepts a double)
    This function sets the pay rate. If a value passed to it
    is within range, it is copied to the payRate member, else
    a default value of 2.50 is set.
   ********************************************************** */

void Payroll::setPayRate(double pRate)
{
    const double MIN_WAGE = 2.50;

    if (pRate >= MIN_WAGE)
    {
        payRate = pRate;
    }
    else
    {
        std::cout << "\nValue for pay rate can't be lower than " << MIN_WAGE << "\n"
                   << "Setting default pay rate: $ " << MIN_WAGE << "\n";
        payRate = MIN_WAGE;
    }
}

/* **********************************************************
            Payroll::calcGrossPay()
    Calculates the gross pay earned by an employee and stores
    the result in the grossPay member variable.
   ********************************************************** */

void Payroll::calcGrossPay()
{
    grossPay = hrsWorked * payRate;
}

PayrollDemo.cpp


/* PayrollDemo.cpp - This program demonstrates the Payroll class. */

#include <iomanip>
#include <iostream>
#include <array>
#include <vector>
#include "Payroll.h"

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

constexpr int NUM_EMPLOYEES = 7;

void getData(array<Payroll, NUM_EMPLOYEES> &);
void displayPData(array<Payroll, NUM_EMPLOYEES> const);

int main()
{
    array<Payroll, NUM_EMPLOYEES> employee{};        // Array of Payroll objects
   
    cout << "ISHIKAWA FRUIT COMPANY - PAYROLL SYSTEM\n\n";

    getData(employee);
    displayPData(employee);

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

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

/* **********************************************************
    getData(accepts an array of Payroll objects)
    This function asks the user for the number of hours worked
    by each employee and the hourly pay rate, then calculates
    the gross pay.
   ********************************************************** */

void getData(array<Payroll, NUM_EMPLOYEES> &employee)
{
    float     hours = 0;
    double payRate = 0.0;

    cout << "Enter the hours worked by " << NUM_EMPLOYEES
          << " employees and their hourly rates.\n";

    for (int index = 0; index < NUM_EMPLOYEES; index++)
    {
        cout << "\nHours worked by employee #"
              << (index + 1) << ": ";
        cin >> hours;

        employee[index].setHrsWorked(hours);

        cout << "Hourly pay rate for employee #"
            << (index + 1) << ": ";
        cin >> payRate;

        employee[index].setPayRate(payRate);
        employee[index].calcGrossPay();
    }
}

/* **********************************************************
   displayPData(accepts an array of Payroll objects)
    This function displays the amount of gross pay each
    employee earned during the week.
   ********************************************************** */

void displayPData(array<Payroll, NUM_EMPLOYEES> const employee)
{
    cout << std::fixed << std::showpoint << std::setprecision(2);
    cout << "\nHere is the gross pay for each employee:\n\n";
   
    for (int index = 0; index < NUM_EMPLOYEES; index++)
    {
        cout << "Employee #" << (index + 1) << " worked " << std::setw(5) << employee[index].getHoursWorked() << " hrs. "
              << ": $ " << std::setw(24) << employee[index].getGrossPay() << "\n";
    }
}


Example Output: