Tuesday, January 31, 2017

Programming Challenge 7.6 - Rain Or Shine

Example File: RainOrShine.txt

/* Rain Or Shine - An amateur meteorologist wants to keep track of weather
   conditions during the past year's three-month summer season and  has
   designated each day as either rainy ('R'), cloudy ('C'), or sunny ('S').
  
   This program stores this information in a 3 x 30 array of characters,
   where the row indicates the month (0 = June, 1 = July, 2 = August) and
   the column indicates the day of the month. (No data is collected for the
   31st of any month.)
  
   The program begins by reading the weather data in from a file. Then it
   creates a report that displays, for each month and for the whole three-
   month period, how many days were rainy, how many were cloudy, and how
   many were sunny.
  
   It also reports which of the three months had the largestAmount number
   of rainy days. */

#include "Utility.h"

/* Global Constant Variables: Months, Days */
const int G_CONST_MONTHS = 3;
const int G_CONST_DAYS = 30;

/* Prototypes: Get meteorologic data, Get count, Get month with most rain,
               Display report */
void getMetData(char[][G_CONST_DAYS]);
void getCount(const char rainOrShine[][G_CONST_DAYS]);
int getMostR(const int[]);
void displayReport(const int[], const int, const int[], const int,
                   const int[], const int, const int);

int main()
{
   char rainOrShine[G_CONST_MONTHS][G_CONST_DAYS] = { };

   /* Call: getMetData */
   getMetData(rainOrShine);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getMetData

   This function accepts an array as its argument. It creates
   a file stream object, reads the data from the file called
   "RainOrShine.txt", processes it, and stores the values in
   the array rainOrShine[][].
   ********************************************************** */

void getMetData(char rainOrShine[][G_CONST_DAYS])
{
   /* Declare: File stream object */
   ifstream metData;

   /* Variables: Months, Days */
   int months = 0,
       days = 0;

   /* Open: File "RainOrShine.txt" */
   metData.open("RainOrShine.txt");
  
   /* If the file was opened successfully, the data will be read into the
      array, and getCount is called to process the data. If there is an
      error, a message is displayed indicating possible sources of errors,
      and the user is asked to exit the program. */
   if (metData)
   {
      for (months = 0; months < G_CONST_MONTHS; months++)
      {
         for (days = 0; days < G_CONST_DAYS; days++)
         {
            metData >> rainOrShine[months][days];
         }
      }

      /* Call: getCount */
      getCount(rainOrShine);
   }
   else
   {
      cout << "An error occured. The file could not be opened and/or\n"
           << "read. Make sure the file exists, the filename is\n"
           << "'RainOrShine.txt', and that the file is not damaged, and\n"
           << "the file has not been moved from the program directory.\n"
           << "\nPress Enter to close this window ...\n";
   }

   /* Close: File "RainOrShine.txt" */
   metData.close();
}

/* **********************************************************
   Definition: getCount

   This function accepts four arrays as argument:
  
      * getMetData[][]
      * frequencyR[]
      * frequencyS[]
      * frequencyC[]
  
   It processes the raw data read into the array from the
   file "RainOrShine.txt". It counts how many days are sunny,
   rainy, and cloudy These values are then stored in one of
   the three arrays. It then accumulates the total sunny,
   rainy and cloudy days.
   ********************************************************** */

void getCount(const char rainOrShine[][G_CONST_DAYS])
{
   /* Array variables: Frequency sunny days, Frequency rainy days,
                       Frequency cloudy days */
   int frequencyS[G_CONST_MONTHS] = { },
       frequencyR[G_CONST_MONTHS] = { },
       frequencyC[G_CONST_MONTHS] = { };

   /* Variables: Total sunny days, Total rainy days, Total cloudy days,
                 Months, Days (loop counters), Month name */
    int totalS = 0,
        totalR = 0,
        totalC = 0,
        days = 0,
        months = 0,
        monthName = 0;
  
   /* The ternary operator determines how many days are sunny, how many
   days are rainy and how many are cloudy. Once either 'S', 'R', or
   'C' are found, the arrays frequencyS, frequencyR and frequencyC
   increment by 1 and store the amount in their subscripts. */
   for (months = 0; months < G_CONST_MONTHS; months++)
   {     
      for (days = 0; days < G_CONST_DAYS; days++)
      {
         rainOrShine[months][days] == 'S' ? frequencyS[months] += 1 :
            rainOrShine[months][days];

         rainOrShine[months][days] == 'R' ? frequencyR[months] += 1 :
            rainOrShine[months][days];

         rainOrShine[months][days] == 'C' ? frequencyC[months] += 1 :
            rainOrShine[months][days];
      }

      totalS += frequencyS[months];
      totalR += frequencyR[months];
      totalC += frequencyC[months];
   }

   /* Call: getMostR, displayReport */
   monthName = getMostR(frequencyR);
               displayReport(frequencyS, totalS, frequencyR, totalR,
                             frequencyC, totalC, monthName);
}

/* **********************************************************
   Definition: getMostR

   This function accepts the following array as argument:

      * frequencyR[]

   It determines the month with most rain and returns this
   value.
   ********************************************************** */

int getMostR(const int frequencyR[])
{
   /* Variables: Month name, Largest amount, Months (loop counter) */
   int monthName = 0,
       largestAmount = 0,
       months = 0;

   /* This loop determines which month was the one with most
      rainy days. Once it is found, largestAmount gets frequencyR[],
      and monthName gets the value of that month. */
   for (months = 0; months < G_CONST_MONTHS; months++)
   {
      if (frequencyR[months] > largestAmount)
      {
         largestAmount = frequencyR[months];
         monthName = months;
      }
   }

   /* Return: monthName */
   return monthName;
}

/* **********************************************************
   Definition: displayReport

   This function accepts the following arrays as arguments:

      * frequencyS[]
      * frequencyR[]
      * frequencyC[]

   It displays a summary for each month, showing how many
   days were sunny, rainy and cloudy, a summary of all
   months, and it reports which month had the most rain.
   ********************************************************** */

void displayReport(const int frequencyS[], const int totalS,
                   const int frequencyR[], const int totalR,
                   const int frequencyC[], const int totalC,
                   const int monthName)
{
   /* Constant: Character name */
   const int CHAR_NAME = 3;

   const string mNamae[G_CONST_MONTHS] = { "June", "July", "August" };
   char charName[CHAR_NAME] = { 'S', 'R', 'C' };

   /* Variables: Months, Count (loop counters) */
   int months = 0,
       cnt = 0;

   /* Display: The report */
   cout << "\t\tMETEOROLOGIC REPORT\n"
      << "\t\t-------------------\n\n\n"
      << "MONTHLY SUMMARY:\n";

   for (months = 0; months < G_CONST_MONTHS; months++)
   {
      cout << "\n" << mNamae[months] << ":\n"
           << "\n-------------------------------------------------\n";

      cout << "Sunny Days: " << setw(3) << right
           << frequencyS[months] << "\t";
      for (cnt = 0; cnt < frequencyS[months]; cnt++)
      {
         cout << " " << charName[0];
      }
      cout << "\n-------------------------------------------------\n";

      cout << "Rainy Days: " << setw(3) << right
           << frequencyR[months] << "\t";
      for (cnt = 0; cnt < frequencyR[months]; cnt++)
      {
         cout << " " << charName[1];
      }
      cout << "\n-------------------------------------------------\n";
  
      cout << "Cloudy Days: " << setw(2) << right
           << frequencyC[months] << "\t";
      for (cnt = 0; cnt < frequencyC[months]; cnt++)
      {
         cout << " " << charName[2];
      }
      cout << "\n-------------------------------------------------\n";
   }

   cout << "\n\nTHREE MONTH SUMMARY:\n"
        << "\n-------------------------------------------------"
        << "--------------------------------------------\n";

      cout << "Sunny Days: " << setw(3) << right << totalS << "\t";
      for (cnt = 0; cnt < totalS; cnt++)
      {
         cout << " " << charName[0];
      }
      cout << "\n-------------------------------------------------"
         << "--------------------------------------------\n";

      cout << "Rainy Days: " << setw(3) << right << totalR << "\t";
      for (cnt = 0; cnt < totalR; cnt++)
      {
         cout << " " << charName[1];
      }
      cout << "\n-------------------------------------------------"
           << "--------------------------------------------\n";

      cout << "Cloudy Days: " << totalC << "\t";
      for (cnt = 0; cnt < totalC; cnt++)
      {
         cout << " " <<  charName[2];
      }
      cout << "\n-------------------------------------------------"
           << "--------------------------------------------\n\n";
     
      cout << "\nMONTH WITH MOST RAIN:\n\n" << mNamae[monthName] << "\n"
           << "-------------------------------------------------\n";
      for (months = 0; months < 1; months++)
      {
         cout << "Rainy Days: " << frequencyR[monthName] << "\t";
         for (cnt = 0; cnt < frequencyR[monthName]; cnt++)
         {
            cout << " " << charName[1];
         }
         cout << "\n-------------------------------------------------\n";
      }
}

Example Output: 






Sunday, January 29, 2017

No Monkey Business

Despite the title of this last challenge, it was all but easy to do it right. There were so many small hurdles in the way that it is difficult for me to name every single one but I will try. Every one caused me to stumble, fall, stand up and retry or rewrite the whole program from scratch.

The very first time i fell was on my first try. About half way through I tried to output to screen the data that was stored for the largest, smallest, average amounts eaten. This worked well for pounds eaten so i tried using the same for the other instances in the code. Consider the following line of code:

cout << "\nOn " << (days[weekdays]) << " ate lbs: " << averageEaten[days];

This was used in the outer loop. The variable days was no array variable, weekdays was. So you could expect that to be causing any problem, wrong output or something. Not at all. It worked in the scope of the function, inside the outer loop. But when used outside it, in the same function, only this time around with loops to iterate through the contents of the relevant subscripts of these arrays, either one of the following problems occurred:

1.) The program would enter an infinite loop
2.) The program displays gibberish and crashes (with some infamous .dll error)

It did not help to change the line of code to something like:

cout << "\nOn " << (weekdays[days]) << " ate lbs: " << averageEaten[days];

So i skipped all the output, left it there, instead stepped through every instance with my debugger to see that my arrays were receiving valid and wanted data. Well, this was simply a way of protracting the problem. There was still the report to be created, separate function - of course, which then showed the flaws in my first revision of code and I had no output that was usable in any way, or rather that would not cause the program to crash on certain instances during execution.

The biggest hurdle at that point was figuring out how to get the smallest amount eaten by each individual monkey. You should think that it works just the same way as the other way when determining the largest amount of food eaten. No, no, no! It is more complex - at least with two dimensional arrays it is not as straightforward as with one dimensional ones. No matter looking at a two-dimensional array as arrays of arrays - one in another. 

This was not the only flaw this first revision had. I was using, what is so called magic-numbers. Meaning that I read there in my book to avoid global variables at all cost. That it meant "... don't use global variables like: int G_WHAT_HAVE_YOU, but instead const int WHAT_HAVE_YOU ..." so the values remain unchanged and no danger occurs from using them, by doing some research about this I found out and used them accordingly in the new revision.

Full of spirit I scrapped the code, added a new file to the project, and started over again.  Another revision more trouble, or rather more of the same trouble as before. My function prototypes were a mess, I used array size declarations which were not needed for instance. Here is an example of one such early function:



Suffice to say that this revision didn't work, the next, the one after that, until I ran out of ideas as to how I should ever solve the challenge. Then I started doing it the other way around. I had worked out all the different parts, meaning getting the least, greatest and average amounts, the total, and even the output in a limited scope. So in my desperate attempt to get something done, I wrote all the arrays, declared their sizes and then kept everything in main instead of separate functions. Would you believe it? Everything worked fine there ... Great. But what with modular programming? Keeping as much of the code out of main and in separate functions, each doing their own thing? Well, it was a template, and a working one. Template file: Monkey.cpp



Then I again tried to separate it all into functions, which worked, as in several of the other revisions. All that would not work, no, that I haven't worked out is is the way to display it. How to get all the data together in one function was the problem, and it was one of the biggest ones all along. This was because of bad choices I made when declaring my variables and functions. At least I guess this was what caused most of it not working the way it was supposed to be.

Yesterday, then desperate and out of ideas, after about 10 to 12 revisions of the same challenge, numerous documents with parts of code, after a particularly bad day when I almost had it all done, closed the IDE and when I opened it, most of the code was back to some hours before ... I closed it i pasted something over working portions of the code, all was gone and I had no idea how I solved the get least amount problem ... Back to square one with this one. Here is what remains from this darkest of days, one single screenshot depicting how far things have grown:

 
So, yesterday I started my next attempt. No, I did not have a plan or clue, so I started playing around. Actually with range-based loops to see what this would do in terms of output. Then I started for real, thinking and looking at all the code that has amassed during the last couple of days. First thing I did was declaring the arrays for monkey names and day names, then working all with output in mind, which should be the final part. And slowly but steadily I found true solutions, no messy ones, no half-heart tries in the hope that I could somehow wing it for certain parts. After some hours of work it was finally finished! You can not imagine my sigh of relief that this Monkey Business was over.

Now, would there have been an easier way to find a solution? Without working hours upon hours on the same problem, and after numerous revisions hardly any ground gained? Certainly. If only I would have asked around for solutions, or simply looking up solutions, then it would have been solved very fast. Why didn't I do this then you might ask? Because then I would have been told what the solution is, I would have implemented it, and what would I have learned from that? Nothing. The challenge, every challenge is, to find one's own solution. Understand, or try hard to, what is going on, how, when and why errors occur. It is these lessons that stick the most, and are most valuable in the long run, to figure things out that way. Because even though every single challenge is limited in scope, what with future projects? If you can't figure out how to write code for one problem, how - then will you be able to apply it in other projects? Similar but not quite? Mind you, I don't say that it would hurt to ask when needed! Figuring it out oneself first, even it takes numerous tries first, is better.

Now, with this difficult challenge out of the way, on the journey goes. I hope that most of the upcoming challenges will be easier to solve - or less troublesome. To my fellow learners, I wish all of you to not stumble and fall over so many hurdles as I did. Give it your all, and success will come in due time.

Programming Challenge 7.5 - Monkey Business

/* Monkey Business - A local zoo wants to keep track of how many pounds
   of food each of its three monkeys eats each day during a typical week.

   This program stores this information in a two-dimensional 3 x 5 array,
   where each row represents a different monkey and each column represents
   a different day of the week.

   First the user has to input the data for each monkey. Then the program
   creates a report that includes the following information:

      * The average amount of food eaten per day by the whole family of
        monkeys
      * The least amount of food eaten during the week by any one monkey
      * The greatest amount of food eaten during the week by any one monkey

   Input Validation: No negative numbers for pounds of food eaten are
   accepted. */

#include "Utility.h"

/* Constants: Global constant number of monkeys,
              Global constant number of weekdays */
const int G_CONST_MONKEYS = 3;
const int G_CONST_DAYS = 5;

/* Prototypes: Get pounds, Get average amount, Get largest amount,
               Get smallest amount, Show data */
void getPounds(double[][G_CONST_DAYS], const string[], const string[]);
void getAverageAmount(double[G_CONST_DAYS], const double[][G_CONST_DAYS]);
void getLargestAmount(double [G_CONST_DAYS], const double [][G_CONST_DAYS]);
void getSmallestAmount(double [G_CONST_DAYS], const double [][G_CONST_DAYS]);
void showData(const double[][G_CONST_DAYS], const double[], const double[],
              const double [], const string[], const string[]);

int main()
{
   /* Array variables: Monkey names, Day names, Pounds eaten,
                       Average eaten, Largest, Smallest */
   const string monkeyNames[G_CONST_MONKEYS] = { "Sora", "Yuki", "Hana" };
   const string dayNames[G_CONST_DAYS] = { "Mon", "Tue", "Wed", "Thu", "Fri" };

   double poundsEaten[G_CONST_MONKEYS][G_CONST_DAYS] = { {0.0} };
   double averageEaten[G_CONST_DAYS] = { 0.0 };
   double largest[G_CONST_DAYS] = { 0.0 };
   double smallest[G_CONST_DAYS] = { 0.0 };

   /* Display: Introduction */
   cout << "\t\tMirano Zoo - Monkey Valley - Feeding Statistics\n\n";

   /* Call: getPounds, getAverage, getLarestAmount, getSmallestAmount,
            showData */
   getPounds(poundsEaten, dayNames, monkeyNames);
   getAverageAmount(averageEaten, poundsEaten);
   getLargestAmount(largest, poundsEaten);
   getSmallestAmount(smallest, poundsEaten);
   showData(poundsEaten, averageEaten, largest,
            smallest, dayNames, monkeyNames);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Defintion: getPounds

   This function accepts three arrays:

      * poundsEaten[][]
      * dayNames[]
      * monkeyNames[]

   It collects the amount eaten by each monkey on every day
   of the week. The result is stored in poundsEaten[][].
   ********************************************************** */

void getPounds(double poundsEaten[][G_CONST_DAYS], const string dayNames[],
               const string monkeyNames[])
{
   /* Variables: Input control, Days, Monkeys (loop counters) */
   int inpCtrl = 0,
       days = 0,
       monkeys = 0;

   /* Get: Amount eaten by any one monkey on any one weekday */
   for (monkeys = 0; monkeys < G_CONST_MONKEYS; monkeys++)
   {
      cout << "" << monkeyNames[monkeys] << ":\n";
      for (days = 0; days < G_CONST_DAYS; days++)
      {
         cout << "" << dayNames[days] << "\t" << " pounds: ";
         cin >> poundsEaten[monkeys][days];

         /* This loop takes care of the input validation. If the user
            enters a value lower than or equal to null, he or she is
            informed about this failure, and asked to repeat the input
            as many times as necessary until a positive value is entered */
         for (inpCtrl = 0; poundsEaten[monkeys][days] <= 0; inpCtrl++)
         {
            cout << "\nInput Failure: The amount of pounds eaten you entered\n"
                 << "was negative and can not be accepted. All input has to\n"
                 << "be positive. Ex.: 0.2, 1.25 ...\n"
                 << "" << dayNames[days] << "\t" << " pounds: ";
            cin >> poundsEaten[monkeys][days];
         }
      }
      cout << endl;
   }
}

/* **********************************************************
   Definition: getAverageAmount

   This function accepts two arrays as arguments:

      * average[]
      * poundsEaten[][]

   It finds and stores the average amount eaten by the family
   of monkeys during the week, and stores the found values in
   average[].
   ********************************************************** */

void getAverageAmount(double average[G_CONST_DAYS],
                      const double poundsEaten[][G_CONST_DAYS])
{
   /* Variable: Total (accumulator) */
   double total = 0.0;

   /* Variables: Days, Monkeys (loop counters) */
   int days = 0,
       monkeys = 0;

   for (days = 0; days < G_CONST_DAYS; days++)
   {
      /* Reset: average[], total */
      average[days] = 0.0;
      total = 0.0;

      /* The total amount of food for each day of the week is
         accumulated by total, and average[] determines and
         stores the average for all three monkeys for each
         day of the week */
      for (monkeys = 0; monkeys < G_CONST_MONKEYS; monkeys++)
      {
         total += poundsEaten[monkeys][days];
         average[days] = total / G_CONST_MONKEYS;
      }
   }
}

/* **********************************************************
   Definition: getLargestAmount

   This function accepts two arrays as arguments:
  
      * largest[]
      * poundsEaten[][]
  
   It determines the largest amount eaten by each monkey and
   stores the result in the array.
   ********************************************************** */

void getLargestAmount(double largest[G_CONST_DAYS],
                      const double poundsEaten[][G_CONST_DAYS])
{
   /* Variable: larger (accumulator) */
   double larger = poundsEaten[G_CONST_MONKEYS][0];

   /* Variables: Days, Monkeys (loop counters) */
   int days = 0,
       monkeys = 0;

   /* These loops determine the largest amount eaten by
      each monkey during the whole week */
   for (monkeys = 0; monkeys < G_CONST_MONKEYS; monkeys++)
   {
      /* Reset: larger */ 
      larger = 0.0;

      /* When a value larger than poundsEaten[][0] is found,
         larger gets this value and passes it to largest[monkeys]
         which stores the three largest amounts eaten by each
         monkey during the whole week */
      for (days = 0; days < G_CONST_DAYS; days++)
      {
         if (larger < poundsEaten[monkeys][days])
            larger = poundsEaten[monkeys][days];
            largest[monkeys] = larger;
      }
   }
}

/* **********************************************************
   Definition: getSmallestAmount

   This function accepts two arrays as arguments:
  
      * smallest[]
      * poundsEaten[][]
  
   It determines the smallest amount eaten by each monkey and
   stores the result in the array.
   ********************************************************** */

void getSmallestAmount(double smallest[G_CONST_DAYS],
                       const double poundsEaten[][G_CONST_DAYS])
{
   /* Variable: smaller (initialized to poundsEaten[][0]) */
   double smaller = poundsEaten[G_CONST_MONKEYS][0];

   /* Variables: Days, Monkeys (loop counters) */
   int days = 0,
       monkeys = 0;

   /* These loops determine the smallest amount eaten by
      each monkey during the whole week */
   for (monkeys = 0; monkeys < G_CONST_MONKEYS; monkeys++)
   {
       /* Variable: smaller (accumulator) */
       double smaller = poundsEaten[G_CONST_MONKEYS][0];
      /* Reset: smaller */
      smaller = poundsEaten[monkeys][0];

      /* When a value smaller than poundsEaten[][0] is found,
         smaller gets this value and passes it to smallest[days]
         which stores the three smallest amounts eaten by each
         monkey during the whole week. */
      for (days = 0; days < G_CONST_DAYS; days++)
      {
         if (poundsEaten[monkeys][days] < smaller)
            smaller = poundsEaten[monkeys][days];
            smallest[monkeys] = smaller;
      }
   }
}

/* **********************************************************
   Definition: showData

   This function accepts six arrays as arguments:

      * poundsEaten[][]
      * average[]
      * largest[]
      * smallest[]
      * dayNames[]
      * monkeyNames[]

   It summarizes what each monkey has eaten, the average
   amount eaten by the whole family of monkeys, the largest
   and smallest amount eaten by each individual member of the
   monkey family.
   ********************************************************** */

void showData(const double poundsEaten[][G_CONST_DAYS], const double average[],
              const double largest[], const double smallest[],
              const string dayNames[], const string monkeyNames[])
{
   /* Variables: Days, Monkeys (loop counters)*/
   int days = 0,
       monkeys = 0;

   /* Set up: Numeric output formatting */
   cout << fixed << showpoint << setprecision(2);

   /* Display: Total amount eaten, Average amount eaten,
               Largest Amount eaten, Smallest amount eaten */
   cout << "\tTotal Amount Eaten:\n"
        << "\t-------------------\n";
   for (monkeys = 0; monkeys < G_CONST_MONKEYS; monkeys++)
   {
      cout << "\n" << monkeyNames[monkeys] << ":\n";
      cout << "----------------------------------------------"
           << "-------------------\n";
      for (days = 0; days < G_CONST_DAYS; days++)
      {
         cout << "" << dayNames[days] << ":"
              << setw(5) << right << poundsEaten[monkeys][days]
              << setw(5) << right;       
      }
      cout << "\n----------------------------------------------"
         << "-------------------\n";
   }
  
   cout << "\n\tAverage Amount Eaten:\n"
        << "\t--------------------\n";
   for (days = 0; days < G_CONST_DAYS; days++)
         cout << "\n" << setw(6) << left << dayNames[days] << ": "
              << setw(25) << right << average[days]
              << setw(5) << right << " lbs";

   cout << "\n\n\tLargest Amount Eaten:\n"
        << "\t--------------------\n";
   for (monkeys = 0; monkeys < G_CONST_MONKEYS; monkeys++)
      cout << "\n" << setw(6) << left << monkeyNames[monkeys] << ": "
           << setw(25) << right << largest[monkeys]
           << setw(5) << right << " lbs";

   cout << "\n\n\tSmallest Amount Eaten:\n"
        << "\t--------------------\n";
   for (monkeys = 0; monkeys < G_CONST_MONKEYS; monkeys++)
      cout << "\n" << setw(6) << left << monkeyNames[monkeys] << ": "
           << setw(25) << right << smallest[monkeys]
           << setw(5) << right << " lbs";
}

Example Output:





Monday, January 23, 2017

Programming Challenge 7.4 - Larger Than N

/* Larger Than N - This program has a function that accepts the following
   three arguments:

      * An array
      * The size of the array
      * A number n

   The function displays all of the numbers in the array that are greater
   than the number n. */

#include "Utility.h"

/* Prototype: Show greater N */
void showLargerThanN(const int[], int, int);

int main()
{
   /* Constant: Array Size */
   const int ARRAY_SIZE = 10;

   /* Variable: Larger N */
   int largerN[ARRAY_SIZE] = { 100, 1294, 128, 15, 31,
                               177, 212, 89, 45, 120 };

   /* Variable: My number, Again */
   int myNumber = 0;
   char again = ' ';

   /* Display: Introduction */
   cout << "\t\tLarger Than N\n\n"
        << "Enter a random number between 1 and 1300 and find out\n"
        << "which of the 10 numbers stored in a so called 'array'\n"
        << "are larger than your number.\n";

   /* Ask the user for a number as long as he or she does not wish
      to quit */
   do
   {
      cout << "\nPlease tell me your number: ";
      cin >> myNumber;

      /* Validate: Input */
      while (myNumber < 0)
      {
         cout << "\nSorry, the number you entered can not be accepted.\n"
              << "It has to be a positive number, at least 1.\n"
              << "Please tell me your number: ";
         cin >> myNumber;
      }

      /* Call: showLargerThanN */
      showLargerThanN(largerN, ARRAY_SIZE, myNumber);

      /* Ask if the user wishes to try another number */
      cout << "\n\nDo you wish to try another number (y/n)? ";
      cin >> again;

      /* Display: A quit message if the user wishes to exit */
      if (again == 'N' || again == 'n')
      {
         cout << "\nNow exiting this program ...\n"
              << "Press Enter to close the window.";
      }
   } while ((again != 'N') && (again != 'n'));

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: showLargerThanN

   This function accepts an array and its size, and a number
   the user has entered, as its arguments. It determines if
   there are numbers larger than the user has entered. If
   there are any, they are then displayed.
   ********************************************************** */

void showLargerThanN(const int largerN[], int sizeOfArray,
                     int myNum)
{
   /* Variable: Compare, Is largest (to get the largest number stored
                in the array, to compare it to myNumber) */
   int compare = 0,
       isLargest = largerN[0];

    
      /* Display: The numbers found to be larger than N */
      for (compare = 0; compare < sizeOfArray; compare++)
      {
         if (largerN[compare] > myNum)
         {
            /* isLargest gets the largest number stored in the array */
            isLargest = largerN[compare];
            cout << "\nThe numbers larger than yours are: "
                 << largerN[compare];
         }
      }

      /* If isLargest is smaller than the number the user entered, a
         message is displayed */
      if (isLargest < myNum)
      {
         cout << "\nThere was no number greater than yours!" << endl;
      }
}

Example Output: 





Two tiny updates

I just wish to let you know that i had to update the code i just released for the last challenge. I totally forgot to add code that sums up the total sales. *Shame on me!* The other thing I wish to inform you about is that I also updated my "Utility.h", so that it now contains #include <vector>

And with this confession made and update announced, back to the next challenge! Good day to all of you fellow learners, and interested visitors. Thanks for dropping by!

Programming Challenge 7.3 - Chips And Salsa

/* Chips And Salsa - This program lets a maker of chips and salsa keep
   track of sales for five different types of salsa:
 
      * Mild, Medium, Sweet, Hot, Zesty
    
   The program uses two parallel 5-element arrays:
 
      * An array of strings that holds the five salsa names
      * An array of integers that holds the number of jars
        sold during the past month for each salsa type.
 
   The salsa names are stored using an initialization list at the time
   the name array is created. The program prompts the user to enter the
   number of jars sold for each type. Once this sales data has been
   entered, the program produces a report that displays the sales for
   each salsa type, total sales, and the names of the highest and lowest
   selling products.
 
   Input Validation: No negative values for number of jars sold are
   accepted. */

#include "Utility.h"

/* Prototypes: Get jars sold, Get bestseller, Get non-seller, Get total sales, Show sales */
void getJarsSold(string[], int [], int);
int getBestseller(const int[], int, int &);
int getNonseller(const int[], int, int &);
int getTotalSales(const int[], int);
void showSales(const string[], const int [], int, int, int, int);

int main()
{
   /* Constants: Number of products, Salsa names, Best selling, Non-seller,
                 Total sales, Number of bestseller, Number of non-seller*/
   const int NUM_PRODUCTS = 5;
   string salsaNames[NUM_PRODUCTS] = { "California Mild", "New Orleans Medium",
                                       "Maine Sweet", "Texas Hot",
                                       "Alabama Zesty" };
   int jarsSold[NUM_PRODUCTS],
       bestSelling = 0,
       nonSeller = 0,
       numBestseller = 0,
       numNonseller = 0,
       totalSales = 0;

   /* Display: Header */
   cout << "\t\tCHABBA CHIPS & SALSA SALES REPORT\n\n";

   /* Call: getJarsSold, getBestseller, getNonseller, getTotalSales, showSales */
   getJarsSold(salsaNames, jarsSold, NUM_PRODUCTS);

   bestSelling = getBestseller(jarsSold, NUM_PRODUCTS, numBestseller);
   nonSeller = getNonseller(jarsSold, NUM_PRODUCTS, numNonseller);
   totalSales = getTotalSales(jarsSold, NUM_PRODUCTS);

   showSales(salsaNames, jarsSold, NUM_PRODUCTS,
             numBestseller, numNonseller, totalSales);
     
   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getJarsSold

   This function accepts two arrays as argument. The user is
   asked to enter the number of jars sold for each salsa
   category.
   ********************************************************** */

void getJarsSold(string salsaNames[], int jarsSold[], int numProducts)
{
   /* Get: The number of jars sold */
   for (int index = 0; index < numProducts; index++)
   {
      cout << "How many jars of " << salsaNames[index]
           << " were sold this month? ";
      cin >> jarsSold[index];

      /* Validate: Input */
      while (jarsSold[index] < 0)
      {
         cout << "\nInput Failure: The number of jars sold has "
              << "to be positive!\n"
              << "How many jars of " << salsaNames[index]
              << " were sold this month? ";
         cin >> jarsSold[index];

      }
   }
}

/* **********************************************************
   Definition: getBestseller

   This function accepts two arrays as arguments. It finds
   and returns the bestselling salsa product.
   ********************************************************** */

int getBestseller(const int jarsSold[], int numProducts,
                        int &numBestseller)
{
   /* Variable: Best selling (gets jarsSold[0] as a
                first value to compare the amount of
                jars sold to) */
   int bestSelling = jarsSold[0];

   for (int index = 0; index < numProducts; index++)
   {
      if (jarsSold[index] > bestSelling)
      {
         bestSelling = jarsSold[index];

         /* When a bestseller is found, numBestseller gets the
            arrays element subscript position */
         numBestseller = index;
      }
   }

   return bestSelling;
}

/* **********************************************************
   Definition: getNonseller

   This function accepts one array as argument. It finds
   and returns the least sold salsa product.
   ********************************************************** */

int getNonseller(const int jarsSold[], int numProducts,
                        int &numNonseller)
{
   /* Variable: Non-selling (gets jarsSold[0] as a
                first value to compare the amount of
                jars sold to) */
   int nonSeller = jarsSold[0];

   for (int index = 0; index < numProducts; index++)
   {
      if (jarsSold[index] < nonSeller)
      {
         nonSeller = jarsSold[index];

         /* When a non-seller is found, numNonseller gets the
         arrays element subscript position */
         numNonseller = index;
      }
   }

   return nonSeller;
}

/* **********************************************************
   Definition: getTotalSales

   This function accepts an array as argument. It determines
   the total number of jars sold, and returns this value.
   ********************************************************** */

int getTotalSales(const int jarsSold[], int numProducts)
{
   /* Variable: Sold total (accumulator) */
   int soldTotal = 0;

   /* Get: The total sales */
   for (int index = 0; index < numProducts; index++)
   {
      soldTotal += jarsSold[index];
   }

   return soldTotal;
}

/* **********************************************************
   Definition: showSales

   This function accepts two integer arrays as arguments. It
   displays the number of sold units for each salsa category,
   and the top and non-seller of each of the five products
   offered.
   ********************************************************** */

void showSales(const string salsaNames[], const int jarsSold[],
               int numProducts, int numBestselling,
               int numNonselling, int totalSales)
{
   /* Display: The formatted output */
   cout << "\n\t\tCHABBA CHIPS & SALSA SALES SUMMARY\n\n"
      << "Product Name" << "\t\t\t\t" << "Units Sold\n"
      << "------------------" << "\t\t\t" << "----------\n";

   for (int index = 0; index < numProducts; index++)
   {
      cout << setw(20) << left << salsaNames[index] << " "
           << setw(29) << right << jarsSold[index] << endl;

   }

   cout << "------------------" << "\t\t\t" << "----------\n"
        << "Total Number Sold " << setw(32) << right << totalSales;
   cout << "\n\nThis months bestseller was: " << salsaNames[numBestselling];
   cout << "\nThis months non-seller was: " << salsaNames[numNonselling];
}

Example Output: 



Sunday, January 22, 2017

Programming Challenge 7.2 - Rainfall Statistics

/* Rainfall Statistics - This program lets the user enter the total
   rainfall for each of 12 months into an array of doubles. The program
   calculates and displays:
  
      * The total rainfall for the year
      * The average monthly rainfall
      * The months with the highest and lowest amounts
     
   Input validation: No negative numbers are accepted for monthly
   rainfall figures. */

#include "Utility.h"

/* Prototypes: Get rainfall data, Get month with highest rainfall, Get
               month with lowest rainfall, Calculate monthly average
               rainfall,  Get total rainfall, Show data */
void getRainfallData(double[], int, string[]);
double getHighest(const double[], int, int &);
double getLowest(const double[], int, int &);
double calcMonthlyAverage(const double[], int);
double getTotalRainfall(const double[], int);
void showData(double, double, double, double, string [], int, int);

int main()
{
   /* Constant: Number of months */
   const int NUM_MONTHS = 12;

   /* Variable: Month names */
   string monthNames[NUM_MONTHS] = { "January", "February", "March",
                                     "April", "May", "June", "July",
                                     "August", "September", "October",
                                     "November", "December" };

   /* Variables: Amount of rainfall, Month with highest rainfall,
                 Month with lowest rainfall, Monthly average,
                 Total amount of rainfall */
   double rainfallAmount[NUM_MONTHS],
          highestRainfall = 0.0,
          lowestRainfall = 0.0,
          monthlyAverage = 0.0,
          totalRainfall = 0.0;

   /* Variable: Name highest, Name lowest */
   int nameHighest = 0,
       nameLowest = 0;

   /* Display: Header */
   cout << "\t\tSTR Data Center: Annual Rainfall Storage\n\n"
        << "Enter the precipitation data for the past 12 months\n"
        << "to get information about the following:\n\n"
        << "\t* The month with the highest amount of rainfall\n"
        << "\t* The month with the lowest amount of rainfall\n"
        << "\t* The average amount of rainfall of months total\n"
        << "\t* The total annual amount of rainfall.\n\n";

   /* Call: getRainfallData, getHighest, getLowest,
            calcMonthlyAverage, getTotalRainfall,
            showData */
   getRainfallData(rainfallAmount, NUM_MONTHS, monthNames);

   highestRainfall = getHighest(rainfallAmount, NUM_MONTHS,
                                nameHighest);

   lowestRainfall = getLowest(rainfallAmount, NUM_MONTHS, nameLowest);

   monthlyAverage = calcMonthlyAverage(rainfallAmount, NUM_MONTHS);
   totalRainfall = getTotalRainfall(rainfallAmount, NUM_MONTHS);

   showData(highestRainfall, lowestRainfall, monthlyAverage,
            totalRainfall, monthNames, nameHighest, nameLowest);
  
   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getRainfallData

   This function accepts two arrays and their sizes as an
   argument. One for the rainfall data, the other as an aid
   during data entry, containing the months names.
   It gets the amount of rainfall for each month of the year
   as input from the user and stores the values in the array.
   ********************************************************** */

void getRainfallData(double rainfall[], int months,
                     string monthNames[])
{
   /* Get: The rainfall amount for each month from the user
      Validate: Input */
   cout << "Enter the amount of rainfall for each month:\n\n";

   for (int counter = 0; counter < months; counter++)
   {
      cout << "Data for "
         << setw(9) << left << (monthNames[counter])
         << setw(5) << right << ": " << right;
      cin >> rainfall[counter];

      while (rainfall[counter] < 0)
      {
         cout << "Input Failure: The amount of rainfall can not "
              << "be negative.\n"
              << "Data for "
            << setw(9) << left << (monthNames[counter])
            << setw(5) << right << ": " << right;
         cin >> rainfall[counter];
      }
   }
}

/* **********************************************************
   Definition: getHighest

   This function accepts an array and its size as arguments.
   It determines the month with the highest rainfall and
   returns the value.
   ********************************************************** */

double getHighest(const double rainfall[], int months,
                  int &nameHighest)
{
   /* Variable: Highest rainfall amount (gets rainfall[0] as a
                first value to compare the amount of rainfall
                to) */
   double highestAmount = rainfall[0];

   /* Determine: The highest amount of rainfall */
   for (int counter = 0; counter < months; counter++)
   {
      /* When the highest amount is found, highestAmount
         gets rainfall[counter] and nameHighest gets the
         counter value of the month with the highest amount
         of rainfall */
      if (rainfall[counter] > highestAmount)
      {
         highestAmount = rainfall[counter];
         nameHighest = counter;
      }
   }

   /* Return: highestAmount */
   return highestAmount;
}

/* **********************************************************
   Definition: getLowest

   This function accepts an array and its size as arguments.
   It determines the month with the lowest rainfall and
   returns the value.
   ********************************************************** */

double getLowest(const double rainfall[], int months,
                 int &nameLowest)
{
   /* Variable: Lowest rainfall amount (gets rainfall[0] as a
                first value to compare the amount of rainfall
                to) */
   double lowestAmount = rainfall[0];

   /* Determine: The highest amount of rainfall */
   for (int counter = 0; counter < months; counter++)
   {
      /* When the lowest amount is found, lowestAmount
         gets rainfall[counter] and nameLowest gets the
         counter value of the month with the lowest amount
         of rainfall */
      if (rainfall[counter] < lowestAmount)
      {
         lowestAmount = rainfall[counter];
         nameLowest = counter;
      }
   }

   /* Return: highestAmount */
   return lowestAmount;
}

/* **********************************************************
   Definition: getTotalRainfall

   This function accepts an array and its size as arguments.
   It calculates the total rainfall and returns the value.
   ********************************************************** */

double getTotalRainfall(const double rainfall[], int months)
{
   /* Variable: Total rainfall (accumulator) */
   double totalRainfall = 0.0;

   /* Get: The total annual amount of rainfall */
   for (int total = 0; total < months; total++)
   {
      totalRainfall += rainfall[total];
   }

   /* Return: totalRainfall */
   return totalRainfall;
}

/* **********************************************************
   Definition: calcMonthlyAverage

   This function accepts an array and its size as arguments.
   It calculates the monthly average amount of rainfall, and
   returns the value.
   ********************************************************** */

double calcMonthlyAverage(const double avgRainfall[], int months)
{
   /* Variable: Monthly average rainfall (accumulator) */
   double monthlyAverage = 0.0;

   /* Calculate: The average monthly amount of rainfall */
   for (int count = 0; count < months; count++)
   {
      monthlyAverage += avgRainfall[count] / months;
   }

   /* Return: monthlyAverage */
   return monthlyAverage;
}

/* **********************************************************
   Definition: showData

   This function accepts five double values containing as
   arguments:

      * Month with highest rainfall
      * Month with lowest rainfall
      * Average monthly rainfall
      * Total rainfall

   Two int values:

      * The value for the name of the month with highest
        rainfall
      * The value for the name of the month with lowest
        rainfall

   An array of string objects and its size, containing the
   names of the 12 months.
  
   It displays the data entered by the user.
   ********************************************************** */

void showData(double monthHighest, double lowestRainfall,
              double monthlyAverage, double totalRainfall,
              string monthNames[], int nameHighest, int nameLowest)
{
   /* Set up: Numeric output formatting */
   cout << fixed << showpoint << setprecision(2);

   cout << "\n\t\tSTR Data Center - Rainfall Data 2016\n\n"
        << "The month with the highest rainfall was "
        << monthNames[nameHighest] << ".\n"
        << "The amount of rainfall was: "
        << monthHighest << " inches.\n\n"
        << "The Month with lowest rainfall was "
        << monthNames[nameLowest] << ".\n"
        << "The amount of rainfall was: "
        << lowestRainfall << " inches.\n\n"
        << "The monthly average rainfall was "
        << monthlyAverage << " inches.\n"
        << "The yearly total rainfall was "
        << totalRainfall << " inches.\n";
}

Example Output: 



Programming Challenge 7.1 - Largest Smallest Array Variable

/* Largest Smallest Array Variable - This program lets the user enter 10
   values into an array. The program displays the largest and smallest
   values stored in the array. */

#include "Utility.h"

/* Prototypes: Get numbers, Get largest, Get smallest */
void getNumbers(int[], int);
int getLargest(const int[], int);
int getSmallest(const int[], int);

int main()
{
   /* Constant: User numbers */
   const int USER_NUMBERS = 10;

   /* Variables: Numbers, Largest number, Smallest number */
   int numbers[USER_NUMBERS],
       largestNumber = 0,
       smallestNumber = 0;

   /* Display: Introduction */
   cout << "\tThe Largest And The Smallest Array Value\n\n"
        << "Enter 10 random numbers, and this program will display\n"
        << "the largest and the smallest number you have entered.\n\n";

   /* Call: getNumbers */
   getNumbers(numbers, USER_NUMBERS);

   /* Call: getLargest, getSmallest */
   largestNumber = getLargest(numbers, USER_NUMBERS);
   smallestNumber = getSmallest(numbers, USER_NUMBERS);

   /* Display: The largest number, The smallest number */
   cout << "\nThe largest number you entered was: "
        << setw(6) << right << largestNumber << endl;

   cout << "The smallest number you entered was:  "
        << setw(4) << right << smallestNumber << endl;

   pauseSystem();
   return 0;
}

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

   This function accepts the array and its size as arguments.
   It asks the user to enter 10 numbers which are then stored
   in the array.
   ********************************************************** */

void getNumbers(int numbers[], int arraySize)
{
   /* Get: The numbers from the user */
   for (int count = 0; count < arraySize; count++)
   {
      cout << "Enter number #" << (count + 1) << ": ";
      cin >> numbers[count];

      while (numbers[count] < 0)
      {
         cout << "Input failure. Only positive numbers are allowed.\n"
            << "Enter number #" << (count + 1) << ": ";
         cin >> numbers[count];
      }
   }
}

/* **********************************************************
   Definition: getLargest

   This function accepts an integer array with 10 elements as
   its argument. It determines and returns the largest number
   entered by the user.
   ********************************************************** */

int getLargest(const int numbers[], int arraySize)
{
   /* Variable: Largest number (gets numbers[0] as a first
                value to compare the numbers that follow to) */
   int largestNumber = numbers[0];

   /* Determine the highest number */
   for (int count = 0; count < arraySize; count++)
   {
      if (numbers[count] > largestNumber)
      {
         largestNumber = numbers[count];
      }
   }

   /* Return: The largest number */
   return largestNumber;
}

/* **********************************************************
   Definition: getSmallest

   This function accepts an integer array as its argument. It
   determines and returns the smallest number entered by the
   user.
   ********************************************************** */

int getSmallest(const int numbers[], int arraySize)
{
   /* Variable: Smallest number (gets numbers[0] as a first
                value to compare the numbers that follow to) */
   int smallestNumber = numbers[0];

   /* Determine the smallest number */
   for (int count = 0; count < arraySize; count++)
   {
      if (numbers[count] < smallestNumber)
      {
         smallestNumber = numbers[count];
      }
   }

   /* Return: The smallest number */
   return smallestNumber;
}

Example Output: