Sunday, February 26, 2017

A Small Lifesign




It has been rather quiet on here the last couple of days. 10 days to be exact. The good news is that neither I nor this blog or my dreams and hopes of achieving my goal are dead. The reason for this not so great silence being that I still work on my current programming challenge. A fun game of TIC-TAC-TOE, or Noughts & Crosses, which - as we all know the best move it is not to play.
By the end of today, or (hopefully) tomorrow at the latest, the code should finally go live for you to enjoy a pleasant game or two. Once it has gone live, I will go into a little more detail about why this has taken so long, and my findings on the way to finish this project. A rather interesting story if I may say so myself.

For now I wish my visitors a pleasant stay, my recurrent visitors thanks for coming by time and again, and all my fellow learners, as always, that they be faster and better in solving the challenges ahead of them than I currently do!

Thursday, February 16, 2017

Programming Challenge 7.17 - Name Search

Example Files: GirlNames.txt
                         BoyNames.txt

/* Name Search - This program reads the contents of the following files
   into two seperate arrays or vectors.

      * GirlNames.txt - This file contains a list of the 200 most popular
        names given to girls born in the United States from 2000 to 2009.

      * BoyNames.txt - This file contains a list of the 200 most popular
        names given to boys born in the United States from 2000 to 2009.

   The user is able to enter a boy's name, a girl's name, or both, and
   the application displays messages indicating whether the names were
   among the most popular. */

#include "Utility.h"

/* Prototypes: Menu, Intro, Get girl names, Get boy Names, Compare girl
               names, Compare boy names */
void menu();
void intro();
int getGirlNames(vector<string> &, vector<int> &);
int getBoyNames(vector<string> &, vector<int> &);
void compareGirlNames(vector<string>, vector<int>);
void compareBoyNames(vector<string>, vector<int>);

int main()
{
   menu();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: Menu

   This function displays a menu which contains the following
   items:

      * Girl Name
      * Boy Name
      * Girl/Boy Name
      * Search (by popularity)
      * Quit

   ********************************************************** */

void menu()
{
   /* Constants: Girl name, Boy name, Girl/Boy name, Quit */
   const int INTRO = 1,
             GIRL_NAME = 2,
             BOY_NAME = 3,
             GIRL_BOY = 4,
             QUIT = 5;

   /* Variable: Select menu item */
   int selectItem = 0;

   /* Vector variables: Girl names, Boy names, Girl popularity
                        index, Boy popularity index */
   vector<string> girlNames, boyNames;
   vector<int> girlPopIndex, boyPopIndex;

   do
   {
      cout << "\t\tPOPULAR GIRL/BOY NAME SEARCH\n\n"
           << "1. INTRODUCTION\n"
           << "2. GIRL NAME\n"
           << "3. BOY NAME\n"
           << "4. GIRL & BOY NAME\n"
           << "5. QUIT\n\n"
           << "Your choice: ";
      cin >> selectItem;
      cout << endl;

      while (selectItem < 1 || selectItem > 5)
      {
         menu();
      }

      switch (selectItem)
      {
         case 1:
            intro();
         break;

         case 2:
            getGirlNames(girlNames, girlPopIndex);       
            girlNames.clear();
         break;

         case 3:
            getBoyNames(boyNames, boyPopIndex);
            boyNames.clear();
        break;

         case 4:
            getGirlNames(girlNames, girlPopIndex);
            getBoyNames(boyNames, boyPopIndex);
            girlNames.clear();
            boyNames.clear();
        break;

         case 5:
            cout << "Good bye!";
         break;
      }

   } while (selectItem != QUIT);
}

/* **********************************************************
   Definition: intro

   This function displays a general introduction to this
   program.
   ********************************************************** */

void intro()
{
   cout << "\t\tPOPULAR GIRL/BOY NAME SEARCH\n\n"
        << "This program allows you to enter a girl name,\n"
        << "a boy name, or a boy and a girl name, to see\n"
        << "how popular they are. If the names are among\n"
        << "the 200 most popular names, a special message\n"
        << "is displayed. Simply choose an item from the\n"
        << "menu, and try it out!\n\n";
}

/* **********************************************************
   Definition: getGirlNames

   This function processes the file "GirlNames.txt". If the
   file is opened successfully, the content is read into the
   vectors:
     
      * gNames - Stores the names
      * gPopCount - Stores the popularity count
   ********************************************************** */

int getGirlNames(vector<string> &gNames, vector<int> &gPopCount)
{
   /* Create file stream object */
   ifstream girlNames;

   /* Variables: Girl names, Popularity counter */
   string gNamesTmp = " ";
   int gCntTmp = 0;

   girlNames.open("GirlNames.txt");

   if (girlNames)
   {
      while (girlNames >> gNamesTmp >> gCntTmp && !girlNames.eof())
      {
         gNames.push_back(gNamesTmp);
         gPopCount.push_back(gCntTmp);
      }

      /* Call: compareBoyNames if the file was processed successfully */
      compareGirlNames(gNames, gPopCount);
   }
   else
   {
      cout << "\nFile open error: The file 'GirlNames.txt' could not\n"
           << "be opened or processed. Please make sure that the filename is\n"
           << "correct and the file is not damaged or has been moved from the\n"
           << "program folder. Please choose 5 to quit this program ...\n\n";

      return 1;
   }
   /* Close file: "GirlNames.txt" */
   girlNames.close();

   return 0;
}

/* **********************************************************
   Definition: getBoyNames

   This function processes the file "BoyNames.txt". If the
   file is opened successfully, the content is read into the
   vectors:
     
      * bNames - Stores the names
      * bPopCount - Stores the popularity count
   ********************************************************** */

int getBoyNames(vector<string> &bNames, vector<int> &bPopCount)
{
   /* Create file stream object */
   ifstream boyNames;

   /* Variables: Boy names, Popularity counter */
   string bNamesTmp = " ";
   int bCntTmp = 0;

   boyNames.open("BoyNames.txt");

   if (boyNames)
   {
      while (boyNames >> bNamesTmp >> bCntTmp && !boyNames.eof())
      {
         bNames.push_back(bNamesTmp);
         bPopCount.push_back(bCntTmp);
      }

      /* Call: compareBoyNames if the file was processed successfully */
      compareBoyNames(bNames, bPopCount);
   }
   else
   {
      cout << "\nFile open error: The file 'BoyNames.txt' could not\n"
         << "be opened or processed. Please make sure that the filename is\n"
         << "correct and the file is not damaged or has been moved from the\n"
         << "program folder. Please choose 5 to quit this program ...\n\n";

      return 1;
   }
   boyNames.close();

   return 0;
}

/* **********************************************************
   Definition: compareGirlNames

   This function accepts the following vectors as arguments:
     
      * girlNames
      * girlPop

   It allows the user to enter a girl name. Once entered, the
   name is compared to the content of the vector, and if it
   is found, the name along with its rank is displayed. If it
   is among the 200 most popular, an additional message is
   displayed.
   ********************************************************** */

void compareGirlNames(vector<string> girlNames, vector<int> girlPop)
{
   /* Variables: Name, Count (loop counter), Error count (accumulator
                 that increments if a name is not found) */
   string name = " ";
   unsigned int count = 0;
   int errCnt = 0;

   /* Ask for a girl name */
   cout << "\nEnter a girl name: ";
   cin >> name;

   /* If the first character in the string that is entered is lowercase,
      it is converted to uppercase */
   if (islower(name.at(0)))
   {
      name[0] = toupper(name[0]);
   }

   /* This loop looks for the existence of a name in the file. If it
      exists, it is displayed. And if it is among the most popular,
      a special message is displayed in addition to that. Else if it
      is in the database, only the name and rank is displayed. If the
      name does not exist, errCnt will increment up to the size of
      girlNames - 1, 999 items. */
   for (count = 0; count < girlNames.size(); count++)
   {
      if (girlNames[count] == name && girlPop[count] <= 300)
      {
         cout << "\n" << girlNames[count]
              << " is among the most popular girl names at place "
              << girlPop[count] << "\n\n";
      }
      else if (girlNames[count] == name)
      {
         cout << "\n" << girlNames[count] << " " << girlPop[count] << "\n\n";
      }     
      else
      {
         errCnt += 1;
      }
   }

   /* If the name was not found, this message is displayed. */
   if (errCnt > 998)
   {
      cout << "\nThe name is not in the database.\n\n";
   }
}

/* **********************************************************
   Definition: compareBoyNames

   This function accepts the following vectors as arguments:
     
      * boyNames
      * boyPop

   It allows the user to enter a boy name. Once entered, the
   name is compared to the content of the vector, and if it
   is found, the name along with its rank is displayed. If it
   is among the 200 most popular, an additional message is
   displayed.
   ********************************************************** */

void compareBoyNames(vector<string> boyNames, vector<int> boyPop)
{
   /* Variables: Name, Count (loop counter), Error count (accumulator
                 that increments if a name is not found) */
   string name = " "; 
   int errCnt = 0;
   unsigned int count = 0;

   /* Get a boy name */
   cout << "Enter a boy name: ";
   cin >> name;

   /* If the first character in the string that is entered is lowercase,
   it is converted to uppercase */
   if (islower(name.at(0)))
   {
      name[0] = toupper(name[0]);
   }

   /* This loop looks for the existence of a name in the file. If it
   exists, it is displayed. And if it is among the most popular,
   a special message is displayed in addition to that. Else if it
   is in the database, only the name and rank is displayed. If the
   name does not exist, errCnt will increment up to the size of
   girlNames - 1, 999 items. */
   for (count = 0; count < boyNames.size(); count++)
   {
      if (boyNames[count] == name && boyPop[count] < 300)
      {
         cout << "\n" << boyNames[count]
              << " is among the most popular boy names at place "
              << boyPop[count] << "\n\n";
      }
      else if (boyNames[count] == name)
      {
         cout << "\n" << boyNames[count] << " " << boyPop[count] << "\n\n";
      }     
      else
      {
         errCnt += 1;
      }
   }

   if (errCnt > 998)
   {
      cout << "\nThe name is not in the database.\n\n";
   }
}

Example Output:









Wednesday, February 15, 2017

Programming Challenge 7.16 - World Series Champions

Example Files: Teams.txt
                         WorldSeriesWinners.txt

/* World Series Champions - This program uses two files:

   * Teams.txt - This file contains a list of several Major League
     baseball teams in alphabetical order. Each team listed in the
     file has won the World Series at least once.

   * WorldSeriesWinners.txt - This file contains a chronological
     list of the World Series' winning teams from 1903 to 2012.
     (The first line in the file is the name of the team that won
     in 1903, and the last line is the name of the team that won in
     2012. The World Series was not played in 1904 and 1994.)

   This program displays the contents of the Teams.txt file on the
   screen and prompts the user to enter the name of one of the teams.
   The program then displays the number of times that team has won
   the World Series in the time period from 1903 to 2012.

     * Tip: Read the contents of the WorldSeriesWinners.txt file into
       an array or vector. When the user enters the name of a team,
       the program should step through the array or vector counting
       the number of times the selected team appears. */

#include "Utility.h"

/* Function prototypes: Display menu, Display intro, Process menu,
   Get teams, Get winners, Display number of wins */
void displayMenu();
void displayIntro();
void processMenu();
void getTeams(vector<string> &);
void getWinners(vector<string> &);
void displayNumWins(const vector<string>, const vector<string>);

int main()
{
   /* Call: displayMenu, processMenu */
   displayMenu();
   processMenu();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: displayMenu

   This function displays a simple menu for the user to
   choose from.
   ********************************************************** */
void displayMenu()
{
   cout << "\t\tMLB - WORLD SERIES CHAMPION DATABASE MAIN MENU\n\n"
      << "1. INTRODUCTION\n"
      << "2. TEAM ROSTER\n"
      << "3. QUIT\n\n"
      << "Your choice: ";
}

/* **********************************************************
   Definition: processMenu

   This function processes the menu selection.
   ********************************************************** */

void processMenu()
{
   /* Constant: View introduction, Team roster, Quit */
   const int INTRO = 1,
             ROSTER = 2,
             QUIT = 3;

   /* Variable: Menu choice */
   int choice = 0;

   /* Vector variables: Teams, Winners, Number of wins */
   vector<string> teams = { " " };
   vector<string> winners = { " " };

   do
   {
      cin >> (choice);

      /* Call: displayIntro, displayMenu, getTeams,
      getWinners, displayNumWins */
      switch (choice)
      {
         case 1:
         displayIntro();
         displayMenu();
         break;

         case 2:

         /* Clear is called to clear vector winners and teams to
            prevent filling them up with the same content again and
            again after every call of the functions. */
         winners.clear();
         teams.clear();

         getTeams(teams);
         getWinners(winners);
         displayNumWins(winners, teams);

         displayMenu();
         break;

         case 3:
         if (choice == QUIT)
         {
            cout << "Thanks for using this program!\n"
                 << "(Now exiting ...)";
         }
         break;
      }
   } while (choice != QUIT);
}

/* **********************************************************
   Definition: displayIntro

   This function introduces the user to the program.
   ********************************************************** */

void displayIntro()
{
   cout << "\n\t\tMLB - WORLD SERIES CHAMPION DATABASE\n\n"
      << "\tThis database contains a number of teams, who, at\n"
      << "\tleast once in the period between 1903 and 2012, won\n"
      << "\tthe Major League Baseball World Series. If you wish to\n"
      << "\tsee how often a particular team has won, you simply have\n"
      << "\tto select: 'TEAM ROSTER' from the menu, enter a name that\n"
      << "\tis displayed in the list, and the result will be displayed\n"
      << "\timmediately.\n\n";
}

/* **********************************************************
   Definition: getTeams

   This function reads in the file "Teams.txt" and stores
   its content in the vector teams.
   ********************************************************** */

void getTeams(vector<string> &teams)
{
   /* Clear is called to clear vector teams to prevent filling it up
      with the same content again and again, every time this function
      enters after the first run. */
   teams.clear();

   /* Create file stream objects: Teams (for "Teams.txt") */
   ifstream teamsFile;

   /* Variable: Team roster (for holding the contents
   of "Teams.txt")*/
   string teamRoster = " ";

   /* Open the files: "Teams.txt", "WorldSeriesWinners.txt" */
   teamsFile.open("Teams.txt");

   /* If the file was opened successfully, and the end of file is
   not reached, the contents of "Teams.txt" is read into teams
   with getline, then processed and stored in the vector teams */
   if (teamsFile)
   {
      while (getline(teamsFile, teamRoster) && !teamsFile.eof())
      { 
         teams.push_back(teamRoster);
      }     
   }
   else
   {
      cout << "\nFile open error: The file 'Teams.txt' could not\n"
         << "be opened or processed. Please make sure that the filename is\n"
         << "correct and the file is not damaged or has been moved from the\n"
         << "program folder.\n\n"
         << "This program will now exit ...";
   }

   /* Close file: "Teams.txt" */
   teamsFile.close();
}

/* **********************************************************
   Definition: getWinners

   This function reads in the file "WorldSeriesWinners.txt",
   and stores its content in the vector teams.
   ********************************************************** */

void getWinners(vector<string> &winners)
{
   /* Create file stream objects: winnersFile
   (for "WorldSeriesWinners.txt) */
   ifstream winnersFile;

   /* Variable: Winning roster (for holding the contents of
   "WorldSeriesWinners.txt") */
   string winningRoster = " ";

   /* Open file: "WorldSeriesWinners.txt" */
   winnersFile.open("WorldSeriesWinners.txt");

   /* If the file was opened successfully, and the end of file is
   not reached, the contents of "WorldSeriesWinners.txt" is
   read into winningRoster with getline, then processed and
   stored in the vector winners */
   if (winnersFile)
   {
      while (getline(winnersFile, winningRoster) && !winnersFile.eof())
      {
         winners.push_back(winningRoster);
      }
   }
   else
   {
      cout << "\nFile open error: The file 'WorldSeriesWinners.txt' could not\n"
         << "be opened or processed. Please make sure that the filename is\n"
         << "correct and the file is not damaged or has been moved from the\n"
         << "program folder.\n\n"
         << "This program will now exit ...";
   }

   /* Close file: "WorldSeriesWinners.txt" */
   winnersFile.close();
}

/* **********************************************************
   Definition: getNumWins

   This function accepts the following vectors:

      * teams<>
      * winners<>

   It asks the user for the team name, then it determines,
   how often a team has won, and displays the result.
   ********************************************************** */

void displayNumWins(const vector<string> winners, const vector<string> teams)
{

   /* Variables: Team name, Count (accumulator to count the number of
      times a team is listed in vector winners) */
   string teamName = " ";
   int cnt = 0;

   /* Display: The team roster */
   cout << "\nTeam Roster:\n\n";
   for (string v : teams)
   {
      cout << v << "\n";
   }
  
   /* Get a team name from the user */
   cout << "\nEnter a team name: ";
   cin.get();
   getline(cin, teamName);

   /* This loop checks to see whehter the teamName matches the input
      and then counts the occurence in the vector winners, which is
      then stored in cnt */
   for (size_t n = 0; n < winners.size(); n++)
   {  
      if (teamName == winners[n])
      {
         cnt++;
      }
   }

   /* Display the number of wins of any given team */
   cout << "\nThe " << teamName << " have won the Major League Baseball "
      << "World Series " << cnt << " times!\n\n";
}


Example Output:

 







Tuesday, February 14, 2017

Programming Challenge 7.15 - Vector Modification

/* Vector Modification - This program is a modification of the National
   Commerce Bank case study presented in Program 7.23. Pin 1, pin 2 and
   pin 3 are vectors instead of arrays. The function is also modified,
   so that it now accepts a vector instead of an array. */

#include "Utility.h"

/* Function prototype: Test pin */
bool testPin(vector<int>, vector<int>);

int main()
{
   /* Variables: Pin 1, Pin 2, Pin 3 */
   vector<int> pin1 = { 2, 4, 1, 8, 7, 9, 0 },
               pin2 = { 2, 4, 6, 8, 7, 9, 0 },
               pin3 = { 1, 2, 3, 4, 5, 6, 7 };

   /* Compare the pins */
   testPin(pin1, pin2) ? cout << "ERROR: pin1 and pin2 report to be the same.\n" :
                         cout << "SUCCESS: pin1 and pin2 are different.\n";

   testPin(pin1, pin3) ? cout << "ERROR: pin1 and pin3 report to be the same.\n" :
                         cout << "SUCCESS: pin1 and pin3 are different.\n";

   testPin(pin1, pin1) ? cout << "SUCCESS: pin1 and pin1 report to be the same.\n" :
                         cout << "ERROR: pin1 and pin1 report to be different.\n";

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: testPin

   This function accepts to vectors:

      * custPin<>
      * databasePin<>

   The vectors are compared. If they contain the same values,
   true is returned. If they contain different values, false
   is returned.
   ********************************************************** */

bool testPin(const vector<int> custPin, const vector<int> databasePin)
{
   for (size_t compare = 0; compare < custPin.size(); compare++)
   {
      if (custPin[compare] != databasePin[compare])
         return false;
   }

   return true;
}

Example Output: 

 



Monday, February 13, 2017

Programming Challenge 7.14 - Lottery Application

/* Lottery Application - This program simulates a lottery. The program
   has an array of five integers named lottery and generates a random
   in the range of 0 through 9 for each element in the array. The user
   is asked to enter five digits, which are stored in an integer array
   named user.
  
   The program compares the corresponding elements in the two arrays
   and keeps count of the digits that match. For example, the following
   shows the lottery array and the user array with sample numbers stored
   in each:
  
        Lottery array:
      * [7][4][9][1][3]

        User array:
      * [4][2][9][7][3]

   The program displays the random numbers stored in the lottery array
   and the number of matching digits. If all of the digits match, a
   message proclaiming the user as a grand prize winner is displayed. */

#include "Utility.h"

/* Function Prototypes: Display menu, Get numbers, Generate random numbers,
   Compare numbers, Display result */
void displayMenu();
void getNumbers(int[], const int);
void generateRndNumbers(int[], const int);
int compareNumbers(const int[], const int[], int[], const int);
void displayResult(const int[], const int[], int[], const int,
                   int);

int main()
{
   /* Call: displayMenu */
   displayMenu();

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: displayMenu

   This function displays a menu with the following items:

   Enter lottery numbers (get the user numbers)
   Start drawing (generate random numbers)
   Display result (to view the result of the drawing)
   Leave the casino (quit the program)
   ********************************************************** */

void displayMenu()
{
   /* Constants: Numbers, Enter numbers, Start lottery, Display result,
                 Quit */
   const int NUMBERS = 5,
             ENTER_NUMBERS = 1,
             START_LOTTERY = 2,
             DISPLAY_RESULT = 3,
             QUIT = 4;

   /* Array variables: lottery, user, result */
   int lottery[NUMBERS] = { 0 };
   int user[NUMBERS] = { 0 };
   int result[NUMBERS] = { 0 };

   /* Variables: Menu choice, Count match */
   int menuChoice = 0,
       countMatch = 0;

   do
   {
      cout << "\t\tRICK'S CAFE AMERICAINE - LOTTERY DRAWING\n\n"
         << "1. Enter lottery numbers\n"
         << "2. Start drawing\n"
         << "3. Display result\n"
         << "4. Leave the Club ...\n\n"
         << "Your choice: ";
      cin >> menuChoice;
      cout << endl;

      while (menuChoice <= 0 || menuChoice > 4)
      {
         cout << "\nInvalid menu choice!\n\n";
         displayMenu();
      }

      /* DO NOT PLACE GENERATE NUMBERS AS SINGLE "CONDITION" IN A DO WHILE LOOP!!!!*/

      switch (menuChoice)
      {
         case 1:
         getNumbers(user, NUMBERS);
         break;

         case 2:   
         generateRndNumbers(lottery, NUMBERS);
         countMatch = compareNumbers(lottery, user, result, NUMBERS);
         break;

         case 3:
         displayResult(lottery, user, result, NUMBERS, countMatch);
         break;
      }

      if (menuChoice == QUIT)
      {
         cout << "Come back and don't forget ... We'll always have Paris!\n\n";
      }

   } while (menuChoice != QUIT);
}

/* **********************************************************
   Definition: getNumbers

   This function accepts the following array as its argument:

      * user[]

   It asks for five lotto numbers from the user and stores
   these in the array.
   ********************************************************** */

void getNumbers(int user[], int numbers)
{
   /* Get number (loop counter) */
   int getNum = 0;

   /* Ask for the numbers */
   for (getNum = 0; getNum < numbers; getNum++)
   {
      cout << "Please enter number " << (getNum + 1) << ": ";
      cin >> user[getNum];

      /* Validate input */
      while (user[getNum] < 0 || user[getNum] > 9)
      {
         cout << "Please enter number " << (getNum + 1) << ": ";
         cin >> user[getNum];
      }
   }
   cout << endl;
}

/* **********************************************************
   Definition: generateRndNumbers

   This accepts the following array as its argument:

      * lottery[]

   It generates and stores in each subscript a random number
   in the range of 1 through 9.
   ********************************************************** */

void generateRndNumbers(int lottery[], const int numbers)
{
   /* Constants: Highest number, Lowest number */
   const int HIGHEST = 9,
             LOWEST = 1;

   /* Seed the random number generator */
   srand((unsigned int)time(NULL));

   /* Variable: Count (loop counter) */
   int cnt = 0;

   while (cnt < numbers)
   {
      lottery[cnt] = (rand() % (HIGHEST - LOWEST + 1)) + LOWEST;
      cnt++;
   }
}

/* **********************************************************
   Definition: compareNumbers

   This function accepts the following arrays as argument:

      * user[]
      * lottery[]
      * result[]

   It compares the numbers entered by the user with those
   randomly generated. The matching numbers are then stored
   in result[] and further processed.
   ********************************************************** */

int compareNumbers(const int lottery[], const int user[], int result[],
                   const int size)
{
   /* Variable: Count (counter variable) */
   int count = 0;

   /* The ternary in this loop compares user[] to lottery[], and if there is a match
      between both, result[] gets the matching numbers */
   for (int compare = 0; compare < size; compare++)
   {
      user[compare] == lottery[compare] ? result[compare] = user[compare] :
                                                            user[compare];
       
      if (result[compare] == lottery[compare])
      {
         count += 1;
      }
   }

   /* Return: count */
   return count;
}

/* **********************************************************
   Definition: displayResult

   This function accepts the following arrays as argument:

      * lottery[]
      * user[]
      * result[]

   It displays the result of each drawing.
   ********************************************************** */
void displayResult(const int lottery[], const int user[], int result[],
                   const int size, int count)
{
   /* Variables: User numbers, Lottery numbers, Result numbers (loop
                 counters */
   int uNum = 0,
       rNum = 0,
       lNum = 0;

   /* Display: The numbers entered by the user */
   cout << "\nYou entered: " << setw(6) << right;
   for (uNum = 0; uNum < size; uNum++)
   {
      cout << user[uNum] << " ";
   }

   /* Display: The drawn numbers */
   cout << "\nDrawn numbers: " << setw(4) << right;
   for (lNum = 0; lNum < size; lNum++)
   {
      cout << lottery[lNum]  << " ";
   }
   cout << endl;

   /* The ternary in this loop determines whether the number stored
   is greater 0, and if so these numbers will be displayed if there
   are any. If there are no matching numbers, - will be displayed in
   their place */
   cout << "Matching numbers: ";
   for (rNum = 0; rNum < size; rNum++)
   {
      result[rNum] > 0 ? cout << (result[rNum]) << " " : cout << "- ";
      result[rNum] = 0;
   }
   cout << endl << endl;

   /* If all numbers match up the winner is congratulated */
   if (count == size)
   {
      cout << "\nWINNER WINNER WINNER! ALL NUMBERS MATCH!\n"
           << "YOU WIN CASABLANCA'S GRAND PRIZE!\n"
           << "$ 1,000,000.00"
           << "Go to 'Rick' for the check!\n\n";
   }
}

Example Output:








Programming Challenge 7.13 - Grade Book Modification

/* Grade Book Modification - A teacher has five students who have taken
   four tests. The teacher uses the following grading scale to assign a
   letter grade to a student, based on the average of his or her four
   test scores.
  
   ------------------------------------------------------
      Test Score                          Letter Grade
   ------------------------------------------------------
      90 - 100                              A
      80 -  89                              B
      70 -  79                              C
      60 -  69                              D
      0  -  59                              F

   This program uses an array of string objects to hold the five student
   names, an array of five characters to hold the five student's letter
   grades, and five arrays of four doubles to hold each student's set of
   test scores.

   The program allows the user to enter each student's name and his or
   her four test NUM_SCORES. It then calculates and displays each student's
   average test score and a letter grade based on the average.

   Input Validation: No test scores less than 0 or greater than 100 are
   accepted.
  
   Modification:
  
      * This program drops each student's lowest score when determining the
        test score averages and letter grades */

#include "Utility.h"

/* Global Constant Variables: Number of students, Number of test scores */
const int NUM_SCORES = 4,
          NUM_STUDENTS = 5;

/* Function Prototypes: Get data, Calculate average, Get letter grades,
                        Display result */
void getData(string[], string[], double[][NUM_SCORES]);
void dropLowest(const double[][NUM_SCORES], double[]);
void calcAverage(const double[][NUM_SCORES], double[], double[]);
void getLetterGrade(const double[], char[]);
void displayResult(const string[], const string[], const double[][NUM_SCORES],
                   const double[], const char[], const double[]);

int main()
{
   /* Array variables: Names, Subjects, Letter grades, Scores,
                       Average */
   string names[NUM_STUDENTS] = { " " };
   string subjects[NUM_SCORES] = { "Math", "Bio", "Chem", "His" };

   char letterGrades[5] = { 'A', 'B', 'C', 'D', 'F' };

   double scores[NUM_STUDENTS][NUM_SCORES] = { { 0.0 } };
   double lowest[5] = { 0.0 };
   double average[NUM_STUDENTS] = { 0.0 };

   /* Call: getData, calcAverage, getLetterGrade, displayResult */
   getData(names, subjects, scores);
   dropLowest(scores, lowest);
   calcAverage(scores, average, lowest);
   getLetterGrade(average, letterGrades);
   displayResult(names, subjects, scores, average, letterGrades, lowest);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getData

   This function accepts the following arrays as arguments:

      * names[]
      * subjects[]
      * scores[]

   This function asks the user for five student names, and
   their four test scores.
   ********************************************************** */

void getData(string names[], string subjects[], double scores[][NUM_SCORES])
{
   /* Variables: Name index, Score index (loop counters) */
   int namesIdx = 0,
       scoresIdx = 0,
       inputCtrl = 0;

   /* Display: Header */
   cout << "\t\tISHIKAWA JHS 114 - STUDENT MONTHLY SCORE REPORT\n\n";

   /* These loops get the five student names from the user which
      are stored in names[], and then ask for the five sets of
      four scores, which are then stored in scores[][] */
   for (namesIdx = 0; namesIdx < NUM_STUDENTS; namesIdx++)
   {
      cout << "Enter name of the student: ";
      cin >> names[namesIdx];

      for (scoresIdx = 0; scoresIdx < NUM_SCORES; scoresIdx++)
      {
         cout << subjects[scoresIdx] << " score: ";
         cin >> scores[namesIdx][scoresIdx];

         /* Input validation */
         for (inputCtrl = 0; scores[namesIdx][scoresIdx] < 0.0 ||
                             scores[namesIdx][scoresIdx] > 100.0; inputCtrl++)
         {
            cout << "\nInput failure: A number below 0.0 or above 100.0\n"
                 << "was entered. Please repeat your input.\n";
            cout << subjects[scoresIdx] << " score: ";
            cin >> scores[namesIdx][scoresIdx];
         }
      }   
      cout << endl;
   }
}

/* **********************************************************
   Definition: dropLowest

   This function accepts the following array as argument:

      * scores[][]
      * lowest[]

   It determines and stores the lowest scores in lowest[].
   ********************************************************** */

void dropLowest(const double scores[][NUM_SCORES], double lowest[])
{
   /* Variables: Lower (accumulator), Index of names, Index of scores
                 (loop counters) */
   int namesIdx = 0,
      scoresIdx = 0;
  
   double lower = scores[NUM_STUDENTS][0];

  
   for (namesIdx = 0; namesIdx < NUM_STUDENTS; namesIdx++)
   {
      /* Reset: Lower */
      lower = scores[namesIdx][0];
     
      /* The lowest values found are stored in lowest[] */
      for (scoresIdx = 0; scoresIdx < NUM_SCORES; scoresIdx++)
      {
         if (scores[namesIdx][scoresIdx] < lower)
            lower = scores[namesIdx][scoresIdx];
            lowest[namesIdx] = lower;
      }
   }
}

/* **********************************************************
   Definition: getAverage

   This function accepts the following array as its argument:

      * scores[][]
      * average[]
      * lowest[]
     
   It calculates the average sum for each student and set of
   test scores stored in the scores[][] array, and stores the
   result in average[].
   ********************************************************** */

void calcAverage(const double scores[][NUM_SCORES], double average[],
                 double lowest[])
{
   /* Variables: Total (accumulator), Scores index,
                 Names index (loop counters) */
   double total = 0.0;

   int scoresIdx = 0,
       namesIdx = 0;
      
   /* These loops calculate the total sum and the average for each
      set of scores. The results are stored in average[] */
   for (int namesIdx = 0; namesIdx < NUM_STUDENTS; namesIdx++)
   {
      /* Reset: total */
      total = 0.0;

      /* Modification: The lowest score dropped is subtracted from
         total and divided by scoresIdx instead of NUM_SCORES */
      for (int scoresIdx = 0; scoresIdx < NUM_SCORES; scoresIdx++)
      {   
        total += scores[namesIdx][scoresIdx];
        average[namesIdx] = (total - lowest[namesIdx]) / scoresIdx;
      }
   }
}

/* **********************************************************
   Definition: getLetterGrade

   This function accepts the following arrays as arguments:
  
      * letterGrades[]
      * average[]
  
   It determines and assigns the letter grades based on the
   average scores of each student, and stores the result in
   grades[].
   ********************************************************** */

void getLetterGrade(const double average[], char grades[])
{
   /* Variable: Name index (loop counter) */
   int namesIdx = 0;

   /* These ternary operators determine and assign the letter grades */
   for (namesIdx = 0; namesIdx < NUM_STUDENTS; namesIdx++)
   {
     average[namesIdx] >= 90.0 && average[namesIdx] <= 100.0 ? grades[namesIdx] = 'A' :
                                                               average[namesIdx];
     average[namesIdx] >= 80.0 && average[namesIdx] <= 89.9 ? grades[namesIdx] = 'B' :
                                                              average[namesIdx];
        average[namesIdx] >= 70.0 && average[namesIdx] <= 79.9 ? grades[namesIdx] = 'C' :
                                                              average[namesIdx];
     average[namesIdx] >= 60.0 && average[namesIdx] <= 69.9 ? grades[namesIdx] = 'D' :
                                                              average[namesIdx];
     average[namesIdx] >= 0.0 && average[namesIdx] <= 59.9 ? grades[namesIdx] = 'F' :
                                                             average[namesIdx];
   }
}

/* **********************************************************
   Definition: displayResults

   This function accepts the following arrays as arguments:
     
      * studentNames[]
      * subjects[]
      * letterGrades[]
      * scores[][]
      * lowest[]
      * average[]
  
   It displays the test results and final letter grades for
   each student.
   ********************************************************** */

void displayResult(const string dNames[], const string dSubjects[],
                   const double dScores[][NUM_SCORES], const double dAverage[],
                   const char dLetterGrade[], const double lowest[])
{
   /* Variable: Index of names, Index of scores (loop counter) */
   int namesIdx = 0,
       scoresIdx = 0;

   /* Display: Header*/
   cout << "\t\tISHIKAWA JHS 114 - STUDENT REPORT CARD\n\n"
        << "\t(The lowest score will be dropped!)\n\n"
        << "Student Name: " << "\t\t" << "Subject: " << "\t\t"
        << "Score:\n";

   /* Display: The scores, averages and letter grades of each student */
   for (namesIdx = 0; namesIdx < NUM_STUDENTS ; namesIdx++)
   {     
      cout << fixed << showpoint << setprecision(1);

      cout << "\n-----------------------------------------------------\n"
           << setw(10) << left << dNames[namesIdx] << endl;

      for (scoresIdx = 0; scoresIdx < NUM_SCORES; scoresIdx++)
      {     
         cout << setw(28) << right << dSubjects[scoresIdx]
            << setw(25) << right << dScores[namesIdx][scoresIdx] << "\n";   
      }

      for (int i = 0; i < 1; i++)
      {
         cout << setw(54) << right << "------\n";
      }

      /* Modification: Display the lowest score that has been dropped */
      cout << "Dropped: "
           << setw(44) << right << lowest[namesIdx] << endl;

      cout << "Average: " << setw(44) << right << dAverage[namesIdx]
           << setw(10) << left;

      cout << "\n-----------------------------------------------------\n";
      cout << "Final Letter Grade: "
           << setw(8) << right << dLetterGrade[namesIdx] << "\n";
   }
}

Example Output: 


Saturday, February 11, 2017

Programming Challenge 7.12 - Grade Book

/* Grade Book - A teacher has five students who have taken four tests.
   The teacher uses the following grading scale to assign a letter grade
   to a student, based on the average of his or her four test scores.
  
   ------------------------------------------------------
      Test Score                          Letter Grade
   ------------------------------------------------------
      90 - 100                              A
      80 -  89                              B
      70 -  79                              C
      60 -  69                              D
      0  -  59                              F

   This program uses an array of string objects to hold the five student
   names, an array of five characters to hold the five student's letter
   grades, and five arrays of four doubles to hold each student's set of
   test scores.

   The program allows the user to enter each student's name and his or
   her four test NUM_SCORES. It then calculates and displays each student's
   average test score and a letter grade based on the average.

   Input Validation: No test scores less than 0 or greater than 100 are
   accepted. */

#include "Utility.h"

/* Global Constant Variables: Number of students, Number of test scores */
const int NUM_SCORES = 4,
          NUM_STUDENTS = 5;

/* Function Prototypes: Get data, Calculate average, Get letter grades,
                        Display result */
void getData(string[], string[], double[][NUM_SCORES]);
void calcAverage(const double[][NUM_SCORES], double[]);
void getLetterGrade(const double[], char[]);

void displayResult(const string[], const string[], const double[][NUM_SCORES],
                   const double[], const char[]);

int main()
{
   /* Array variables: Names, Subjects, Letter grades, Scores,
                       Average */
   string names[NUM_STUDENTS] = { " " };
   string subjects[NUM_SCORES] = { "Math", "Bio", "Chem", "His" };

   char letterGrades[NUM_STUDENTS] = { 'A', 'B', 'C', 'D', 'F' };

   double scores[NUM_STUDENTS][NUM_SCORES] = { { 0.0 }, { 0.0 } };
   double average[NUM_STUDENTS] = { 0.0 };

   /* Call: getData, calcAverage, getLetterGrade, displayResult */
   getData(names, subjects, scores);
   calcAverage(scores, average);
   getLetterGrade(average, letterGrades);
   displayResult(names, subjects, scores, average, letterGrades);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getData

   This function accepts the following arrays as arguments:

      * names[]
      * subjects[]
      * scores[]

   This function asks the user for five student names, and
   their four test scores.
   ********************************************************** */

void getData(string names[], string subjects[], double scores[][NUM_SCORES])
{
   /* Variables: Name index, Score index (loop counters) */
   int namesIdx = 0,
       scoresIdx = 0,
       inputCtrl = 0;

   /* Display: Header */
   cout << "\t\tISHIKAWA JHS 114 - STUDENT MONTHLY SCORE REPORT\n\n";

   /* These loops get the five student names from the user which
      are stored in names[], and then ask for the five sets of
      four scores, which are then stored in scores[][] */
   for (namesIdx = 0; namesIdx < NUM_STUDENTS; namesIdx++)
   {
      cout << "Enter name of the student: ";
      cin >> names[namesIdx];

      for (scoresIdx = 0; scoresIdx < NUM_SCORES; scoresIdx++)
      {
         cout << subjects[scoresIdx] << " score: ";
         cin >> scores[namesIdx][scoresIdx];

         /* Input validation */
         for (inputCtrl = 0; scores[namesIdx][scoresIdx] < 0.0 ||
                             scores[namesIdx][scoresIdx] > 100.0; inputCtrl++)
         {
            cout << "\nInput failure: A number below 0.0 or above 100.0\n"
                 << "was entered. Please repeat your input.\n";
            cout << subjects[scoresIdx] << " score: ";
            cin >> scores[namesIdx][scoresIdx];
         }
      }   
      cout << endl;
   }
}

/* **********************************************************
   Definition: getAverage

   This function accepts the following array as its argument:

      * scores[][]
      * average[]

   It calculates the average sum for each student and set of
   test scores stored in the scores[][] array, and stores the
   result in average[].
   ********************************************************** */

void calcAverage(const double scores[][NUM_SCORES], double average[])
{
   /* Variables: Total (accumulator), Scores index,
                 Names index (loop counters) */
   double total = 0.0;

   int scoresIdx = 0,
       namesIdx = 0;
      
   /* These loops calculate the total sum and the average for each
      set of scores. The results are stored in average[] */
   for (int namesIdx = 0; namesIdx < NUM_STUDENTS; namesIdx++)
   {
      /* Reset: total */
      total = 0.0;

      for (int scoresIdx = 0; scoresIdx < NUM_SCORES; scoresIdx++)
      {
        total += scores[namesIdx][scoresIdx];
        average[namesIdx] = total / NUM_SCORES;
      }
   }
}

/* **********************************************************
   Definition: getLetterGrade

   This function accepts the following arrays as arguments:
  
      * letterGrades[]
      * average[]
  
   It determines and assigns the letter grades based on the
   average scores of each student, and stores the result in
   grades[].
   ********************************************************** */

void getLetterGrade(const double average[], char grades[])
{
   /* Variable: Name index (loop counter) */
   int namesIdx = 0;

   /* These ternary operators determine and assign the letter grades */
   for (namesIdx = 0; namesIdx < NUM_STUDENTS; namesIdx++)
   {
     average[namesIdx] >= 90.0 && average[namesIdx] <= 100.0 ? grades[namesIdx] = 'A' :
                                                               average[namesIdx];
     average[namesIdx] >= 80.0 && average[namesIdx] <= 89.9 ? grades[namesIdx] = 'B' :
                                                              average[namesIdx];
        average[namesIdx] >= 70.0 && average[namesIdx] <= 79.9 ? grades[namesIdx] = 'C' :
                                                              average[namesIdx];
     average[namesIdx] >= 60.0 && average[namesIdx] <= 69.9 ? grades[namesIdx] = 'D' :
                                                              average[namesIdx];
     average[namesIdx] >= 0.0 && average[namesIdx] <= 59.9 ? grades[namesIdx] = 'F' :
                                                             average[namesIdx];
   }
}

/* **********************************************************
   Definition: displayResult

   This function accepts the following arrays as arguments:
     
      * studentNames[]
      * subjects[]
      * letterGrades[]
      * scores[][]
      * average[]
  
   It displays the test results and final letter grades for
   each student.
   ********************************************************** */

void displayResult(const string dNames[], const string dSubjects[],
                   const double dScores[][NUM_SCORES], const double dAverage[],
                   const char dLetterGrade[])
{
   /* Variable: Index of names, Index of scores (loop counter) */
   int namesIdx = 0,
       scoresIdx = 0;

   /* Display: Header*/
   cout << "\t\tISHIKAWA JHS 114 - STUDENT REPORT CARD\n\n"
        << "Student Name: " << "\t\t" << "Subject: " << "\t\t"
        << "Score:\n";

   /* Display: The scores, averages and letter grades of each student */
   for (namesIdx = 0; namesIdx < NUM_STUDENTS; namesIdx++)
   {     
      cout << fixed << showpoint << setprecision(1);

      cout << "\n-----------------------------------------------------\n"
           << setw(10) << left << dNames[namesIdx] << endl;

      for (scoresIdx = 0; scoresIdx < NUM_SCORES; scoresIdx++)
      {     
         cout << setw(28) << right << dSubjects[scoresIdx]
            << setw(25) << right << dScores[namesIdx][scoresIdx] << "\n";           
      }

      for (int i = 0; i < 1; i++)
      {
         cout << setw(54) << right << "------\n";
      }

      cout << "Average: " << setw(44) << right << dAverage[namesIdx]
           << setw(10) << left;
      cout << "\n-----------------------------------------------------\n";
      cout << "Final Letter Grade: "
           << setw(8) << right << dLetterGrade[namesIdx] << "\n";
   }
}

Example Output: