Chapter 8 Programming Challenges By: Phillip Lee, May 1, 2015



Download 218.07 Kb.
Date17.05.2017
Size218.07 Kb.
#18607
Chapter 8 Programming Challenges

By: Phillip Lee, May 1, 2015

Pre-Homework 1:

#include

using namespace std;

int main()

{

//declare an integer array named numbers, size 5

int numbers[5];

for (int i = 0; i < 5; i++)

{

//assign 100, 200, 300, 400, 500, in the array

numbers[i] = 100 * (i + 1);

cout << numbers[i] << endl;

}

system("pause");

return 0;

}

Pre-Homework 2:

#include

#include

using namespace std;

int main()

{

//declare a 2-d array named numbers
int numbers[2][3] = { { 6, 10, 9 }, { 4, 5, 8 } };
for (int row = 0; row < 2; row++)

{

for (int column = 0; column < 3; column++)

{

cout <

}

cout << endl;

}

system("pause");

return 0;

}
Pre-Homework 3:

Develop a C++ program that prompts the user to enter a row and a column number, and a special character. The program displays a rectangle with the assigned character.

#include

using namespace std;
int row, column;

char character;

void display(int r, int c, char s);
int main()

{

cout << "Please enter row number: \n";

cin >> row;
cout << "Please enter column number: \n";

cin >> column;
cout << "Enter a character: \n";

cin >> character;
display(row, column, character);
system("pause");

return 0;

}

void display(int r, int c, char s)

{

for (int i = 0; i < r; i++)

{

for (int i = 0; i < c; i++)

{

cout << s << " ";

}

cout << endl;

}

}

1. Perfect Scores

Write a modular program that accepts up to 20 integer test scores in the range of 0 to

100 from the user and stores them in an array. Then main should report how many perfect scores were entered (i.e., scores of 100), using a value-returning countPerfect function to help it.



// Chapter 8 - Programming Challenge 1, Perfect Scores

// This program counts the number of perfect scores stored in an integer array.

#include

using namespace std;
// Function prototypes

int getScores(int[]);

int countPerfect(int[], int);
int main()

{

const int SIZE = 5;

int array[SIZE],

numScores;
// Explain the program to the user

cout << "This program will allow you to enter up to 20 scores \n"

<< "and will then report how many perfect scores were entered. \n\n";
// Call a function to input the scores into array.

numScores = getScores(array);
// Report the results

cout << "\nThe " << numScores << " scores you entered include "

<< countPerfect(array, numScores) << " perfect scores.";
return 0;

}
/*******************************************************

* getScores *

* Accepts scores input by the user, stores them in an *

* array, and counts them. *

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

int getScores (int array[])

{

int num,

pos = 0;



do

{ cout << "\nEnter a score 0 - 100 (or -1 to quit): ";

cin >> num;
if (num >= 0 && num <= 100) // If num is valid,

{ array[pos] = num; // store it and go

pos++; // to the next array position.

}

else if (num > 100) // If num is invalid, display an error message.

{ cout << "\nInvalid score. Scores many not be greater than 100. \n\n";

}

// else the end sentinel was entered, so do nothing.
} while (num >= 0 && pos < 5); // Loop again as long as the end sentinel

// has not yet been entered and the number

// of array locations has not been exceeded.



return pos; // The current value of pos equals the number of scores.

}
/*******************************************************

* countPerfect *

* Counts the number of "perfect" (i.e., 100) scores *

* in the array of integers passed to it. *

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

int countPerfect(int array[], int numElts)

{

int numPerfect = 0;
for (int i = 0; i < numElts; i++)

{

if (array[i] >= 90)

numPerfect++;

}

return numPerfect;

}

2. Roman Numeral Converter



Write a program that displays the roman numeral equivalent of any decimal number between 1 and 20 that the user enters. The roman numerals should be stored in an array of strings and the decimal number that the user enters should be used to locate the array element holding the roman numeral equivalent. The program should have a loop that allows the user to continue entering numbers until an end sentinel of 0 is entered.

// Chapter 8 - Programming Challenge 2, Roman Numeral Converter

// This program displays the roman numeral equivalent of an

// enterered decimal number. The roman numerals are stored in an array.

#include

#include

#include

using namespace std;
//Function prototype

int getValidNum();
const int MAX_NUM = 20;
const string romanNums[] = {" ", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X",

"XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX" };

int main()

{

int decNum; // The user entered decimal number to be converted
cout << "Decimal to Roman Numeral Converter \n\n";

decNum = getValidNum();
while (decNum != 0) // While the end sentinel has not been entered, process the number

{

cout << "The roman numeral equivalent of " << decNum << " is " << romanNums[decNum] << "\n\n";
decNum = getValidNum();

}

return 0;

}
/***************************************************

* getValidNum *

* Inputs, validates, and returns a valid integer. *

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

int getValidNum()

{

int num;

cout << "\nEnter a decimal number 1-" << MAX_NUM << " (or 0 to quit): ";

cin >> num;
while (num < 0 || num > 20)

{

cout << "That is not a valid number.\n"

<< "\nEnter a decimal number 1-" << MAX_NUM << ": ";

cin >> num;

}

return num;

}

3. Chips and Salsa



Write a program that lets a maker of chips and salsa keep track of their sales for five different types of salsa they produce: mild, medium, sweet, hot, and zesty. It should use two parallel five-element arrays: an array of strings that holds the five salsa names and an array of integers that holds the number of jars sold during the past month for each salsa type. The salsa names should be stored using an initialization list at the time the name array is created. The program should prompt the user to enter the number of jars sold for each type. Once this sales data has been entered, the program should produce a report that displays sales for each salsa type, total sales, and the names of the highest selling and lowest selling products.

// Chapter 8 - Programming Challenge 3, Chips and Salsa

// This program produces a sales report for a salsa maker who markets

// 5 types of salsa. It includes total sales for all products and

// identifies the highest and lowest selling product. Two parallel

// arrays are used to store the salsa names and quantities sold of each.

#include

#include

#include

using namespace std;
// Function prototypes

int getSalesData(string [], int []);

int posOfLargest(int []);

int posOfSmallest(int []);

void displayReport(string [], int [], int);
const int SIZE = 5;
int main()

{
string name[SIZE] = {"mild ", "medium", "sweet ", "hot ", "zesty "};

int sales[SIZE]; // Holds jars sold for each salsa type
int totalJarsSold = getSalesData(name, sales);



displayReport(name, sales, totalJarsSold);
return 0;

}
/************************************************************

* getSalesData *

* Accepts the sales figures for each salsa type and stores *

* them in the array passed to the function, as well as *

* accumulating and returning the total of all salsas sold. *

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

int getSalesData(string name[], int sales[])

{

int total = 0;



for (int type = 0; type < SIZE; type++)

{

cout << "Jars sold last month of " << name[type] << ": ";

cin >> sales[type];



while (sales[type] < 0)

{ cout << "Jars sold must be 0 or more. Please re-enter: ";

cin >> sales[type];

}



total += sales[type];

}

return total;

}

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

* displayReport *

* Displays the sales report using information from the *

* arrays passed to it.

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

void displayReport(string name[], int sales[], int total)

{

int hiSalesProduct = posOfLargest(sales);

int loSalesProduct = posOfSmallest(sales);



cout << "\n\n Salsa Sales Report \n\n";

cout << "Name Jars Sold \n";

cout << "____________________\n";
for (int type = 0; type < SIZE; type++)

cout << name[type] << setw(11) << sales[type] << endl;
cout << "\nTotal Sales: " << total << endl;

cout << "High Seller: " << name[hiSalesProduct] << endl;

cout << "Low Seller : " << name[loSalesProduct] << endl;

}
/************************************************************

* posOfLargest *

* Finds and returns the subscript of the array position *

* holding the largest value in the array passed to the *

* function. *

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

int posOfLargest(int array[])

{

int indexOfLargest = 0;



for (int pos = 1; pos < SIZE; pos++)

{

if (array[pos] > array[indexOfLargest])

indexOfLargest = pos;

}

return indexOfLargest;

}

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

* posOfSmallest *

* Finds and returns the subscript of the array position *

* holding the smallest value in the array passed to the *

* function. *

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

int posOfSmallest(int array[])

{

int indexOfSmallest = 0;



for (int pos = 1; pos < SIZE; pos++)

{

if (array[pos] < array[indexOfSmallest])

indexOfSmallest = pos;

}

return indexOfSmallest;

}

4. 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. Write a program that stores this information in a two-dimensional 3 × 7 array, where each row represents a different monkey and each column represents a different day of the week. The program should first have the user input the data for each monkey. Then it should create a report that includes the following information:

• 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.



// Chapter 8 - Programming Challenge 4, Monkey Business

// This program uses a 2-dimensional array to store data on

// monkey food consumption. The array is passed to functions

// that find total, least, and greatest food consumption.

#include

#include

#include

using namespace std;
const int NUM_MONKEYS = 3;

const int NUM_DAYS = 7;
// Function prototypes

void getData(double[][NUM_DAYS]);

double findGroupTotal(double[][NUM_DAYS]);

double findOneTotal (double[][NUM_DAYS], int);

double findLeastTotal(double[][NUM_DAYS]);

double findGreatestTotal(double[][NUM_DAYS]);
int main()

{

// Create a 2-D array to hold the pounds of food consumed

// by each monkey on each day of the week

double food[NUM_MONKEYS][NUM_DAYS];
// Call the getData function to input the data into the array

getData(food);
// Display the average amount of food the monkeys ate per day, and the

// least amount and greatest amount eaten all week by any one monkey.

cout << "\n\nAverage amount of food eaten per day \n"

<< "by the entire family of monkeys = "

<< (findGroupTotal(food) / NUM_DAYS) << " pounds. \n\n";
cout << "Least amount of food eaten during the week \n"

<< "by any one monkey = " << findLeastTotal(food) << " pounds. \n\n";
cout << "Greatest amount of food eaten during the week \n"

<< "by any one monkey = " << findGreatestTotal(food) << " pounds. \n";
return 0;

}
/*****************************************************

* getData *

* Fills the array with data. *

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

void getData(double food[][NUM_DAYS])

{

for (int monkey = 0; monkey < NUM_MONKEYS; monkey++)

{

cout << "\nEnter pounds of food eaten by monkey #"

<< (monkey+1) << " on \n";

for (int day = 0; day < NUM_DAYS; day++)

{

cout << "day " << (day+1) << ": ";

cin >> food[monkey][day];

while (food[monkey][day] < 0.0)

{

cout << "food eaten cannot be less than 0. Please re-enter\n";

cout << "day " << (day+1) << ": ";

cin >> food[monkey][day];

}

}

}

}
/*****************************************************

* findGroupTotal *

* Returns the total of all values in the array. *

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

double findGroupTotal(double food[][NUM_DAYS])

{

double total = 0.0;
for (int monkey = 0; monkey < NUM_MONKEYS; monkey++)

{

for (int day = 0; day < NUM_DAYS; day++)

total += food[monkey][day];

}

return total;

}

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

* findOneTotal *

* Finds and returns the amount of food eaten during *

* the week by one particular monkey. It does this by*

* totaling and returning the values in the one row *

* of the array representing the desired monkey. *

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

double findOneTotal (double food[][NUM_DAYS], int thisMonkey)

{

double total = 0.0;
for (int day = 0; day < NUM_DAYS; day++)

total += food[thisMonkey][day];
return total;

}



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

* findLeastTotal *

* Finds and returns the smallest row total. *

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

double findLeastTotal (double food[][NUM_DAYS])

{

double thisMonkeyTotal;

double leastTotal;



// Set leastTotal to the first monkey's total food consumption

leastTotal= findOneTotal(food, 0);
// Check if any other monkey consumed less food

for (int thisMonkey = 1; thisMonkey < NUM_MONKEYS; thisMonkey++)

{

thisMonkeyTotal = findOneTotal(food, thisMonkey);

if (thisMonkeyTotal < leastTotal)

leastTotal = thisMonkeyTotal;

}

return leastTotal;

}
/*****************************************************

* findGreatestTotal *

* Finds and returns the largest row total. *

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

double findGreatestTotal (double food[][NUM_DAYS])

{

double thisMonkeyTotal;

double greatestTotal;
// Set greatestTotal to the first monkey's total food consumption

greatestTotal= findOneTotal(food, 0);
// Check if any other monkey consumed more food

for (int thisMonkey = 1; thisMonkey < NUM_MONKEYS; thisMonkey++)

{

thisMonkeyTotal = findOneTotal(food, thisMonkey);

if (thisMonkeyTotal > greatestTotal)

greatestTotal = thisMonkeyTotal;

}

return greatestTotal;

}

5. 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’). Write a program that stores this information in a 3 × 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. Note that data is not being collected for the 31st of any month. The program should begin by reading the weather data in from a file. Then it should create 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 should also report which of the three months had the largest number of rainy days. Data for the program can be found in the RainOrShine.dat file.

// Chapter 8 - Programming Challenge 5, Rain or Shine

// This program creates a weather report for the 3 summer months,

// using data read in from the RainOrShine.dat file located in the

// same directory as this program.. Students must be sure to place

// a copy of this data file in their program project directory.

// TO simplify the program, there are 30 days of data for each month.

#include

#include

#include

#include

using namespace std;
const int NUM_MONTHS = 3,

DAYS_IN_MONTH = 30;
const string name[NUM_MONTHS] = { "June", "July", "August" };
// Function prototype

void readFileData(char[][DAYS_IN_MONTH]);
int main()

{

char dayType[NUM_MONTHS][DAYS_IN_MONTH];
int rainy, // Counts number of days of each type

cloudy, // during one particular month

sunny,

rainyTotal = 0, // Counts number of days of each type

cloudyTotal = 0, // during 3-month period

sunnyTotal = 0,

wettestMonth, // Index of rainiest month

wettestMonthsRain = -1; // Number of rainy days in rainiest month
// Call function to read in the weather data and store it in the array

readFileData(dayType);
// Print report heading

cout << " Summer Weather Report\n\n"

<< "Month Rainy Cloudy Sunny\n"

<< "_____________________________\n";
// Accumulate and display weather statistics

for (int month = 0; month < NUM_MONTHS; month++)

{

// Reset accumulators

rainy = cloudy = sunny = 0;
// Accumulate weather statistics for current month

for (int day = 0; day < DAYS_IN_MONTH; day++)

{

if (dayType[month][day] == 'R')

rainy++;

else if (dayType[month][day] == 'C')

cloudy++;

else

sunny++;

}

// Add monthly totals to grand totals

rainyTotal += rainy;

cloudyTotal += cloudy;

sunnyTotal += sunny;
// Determine if this month is the rainiest so far

if (rainy > wettestMonthsRain)

{

wettestMonthsRain = rainy;

wettestMonth = month;

}

// Display this month's results

cout << left << setw(6) << name[month]

<< right << setw(6) << rainy << setw(8) << cloudy

<< setw(7) << sunny << endl;

}

// Display summary data

cout << "_____________________________\n";

cout << "Totals" << setw(6) << rainyTotal << setw(8)

<< cloudyTotal << setw(7) << sunnyTotal << endl << endl;

cout << "The month with the most rainy days was "

<< name[wettestMonth] << ".\n";
system("pause");

return 0;

}
/************************************************************

* readFileData *

* This function fills the 2D array passed to it with data *

* from a file. *

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

void readFileData(char dayType[][DAYS_IN_MONTH])

{

ifstream weatherData;
//Open data file

weatherData.open("RainOrShine.dat");

if (!weatherData)

{

cout << "Error opening data file.\n";

exit(EXIT_FAILURE); // Exit program with an error code

}
// Else, if file was opened correctly, read weather data into the array

for (int month = 0; month < NUM_MONTHS; month++)

{

for (int day = 0; day < DAYS_IN_MONTH; day++)

weatherData >> dayType[month][day];

}

// Close the data file

weatherData.close();

}

Download 218.07 Kb.

Share with your friends:




The database is protected by copyright ©ininet.org 2024
send message

    Main page