Divide & Conquer

This post is being created to display the Divide and Conquer problem solving strategy.

While taking a C++ programming class, I was suddenly hit with a great deal work than I had expected. The work seemed completely overwhelming, and I felt a bit overwhelmed. To reduce the work load I have decided to break down the work to be performed into much smaller, byte size pieces. To do this, I must take the full scope of each assignment and break it down into much smaller, “byte” size pieces.

There are 3 different problem sets. The first entails the use of the CodeBlocks IDE, the second and third are both lab assignments.

References:
Dale, N. & Weems, C. (2010). Programming and Problem Solving with C++, 5th edition, Jones and Bartlett Publishers, Sudbury, MA.
Dale, N (2010). A Labratory Course in C++, 5th edition, Jones and Bartlett Publishers, Sudbury, MA.

 

Problem Set 1: CodeBlocks IDE

Requirements:
All lab assignments must be saved as a project file, and each file must work independently of each other yet work together as a complete software package.

The resolution to this was actually quite simple. Each independent file was created by formatting the file as a function other than main. The main file (function) then included references to the other functions. The main file (function) also included internal functions so that a user could enter the program number of there choice or enter zero to exit the program. The program loops indefinitely, requesting a program to run until the user enters the number zero.

Here is the code:
// Example of software package to be run from codeblocks  or other IDE project file.
// This program asks the user to enter the number of a program
// or the number 0 to exit the program.
// Author: Michael A. Stratton, 2011 http://www.mikestratton.net/
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
//
#include <iostream>

using namespace std;

//**************************************************************
//**************************************************************
// Import external programs
void richUncle();
void richUncle_unresolved();
// End of Imported Programs
//**************************************************************
//**************************************************************

//**************************************************************
//**************************************************************
// internal programs
void selectProgram(); // used to gather user input

int programNumber; // global variable to assoiciate program number
// end of internal programs
//**************************************************************
//**************************************************************

//**************************************************************
//**************************************************************
// Main Function
int main()
{
selectProgram(); // function requesting user input for program

while (programNumber == 0)
{
return 1;
}
while(programNumber != 1 &&
programNumber != 2)
{
cout << “Your entry was not reconized.” << endl << endl;
cin >> programNumber;
}

while(programNumber == 1)
{
richUncle();
selectProgram();
}
while(programNumber == 2)
{
richUncle_unresolved();
selectProgram();
}

return 0;
}
// end main function
//**************************************************************
//**************************************************************

//**************************************************************
//**************************************************************
// function requesting user input
void selectProgram() // used to request user input.
{
cout << “Welcome to Lab 8-6 Professor Sanford!” << endl << endl;
cout << “Please select a program to run.” << endl;
cout << “To run the richUncle program enter 1” << endl;
cout << “To run the richUncle_unresolved program enter 2” << endl;
cout << “To end this program, enter 0” << endl;
cin >> programNumber;
}
// end function requesting user input
//**************************************************************
//**************************************************************

 

 

Problem Set 2: Lab 8-6 Case Study Maintenance

Requirements:
Exercise 1:
Refactor an existing program. Recall that in a refactoring situation, the functional decomposition is done in light of the know solution to the problem. In many cases. it involves arragning existing statements into encapsulated functions so that the code is easer to understand and modify.
Exercise 2:
How many solutions does your refactored solution have?
Exercise 3:
List each function name along with the parameter list.

The first step in this was to create a flow chart of how the refactored solution would look. To do this I used Microsoft Visio to create a simplistic flow chart.
Click here to view the flow chart: Lab 8-6 Visio Flowchart
* Flowchart works best if viewed in Internet Explorer.

The biggest problem came as a result of having to refactor the existing code into separate functions.

Here is the existing code:

//********************************************************************
// Rich Uncle Program
// Percentage of characters in the file that belong to five categories:
// uppercase characters,lowercase characters, decimal digits, blanks,
// and end-of-sentence punctuation marks
// Assumptions: Input file is not empty and percentages are based
// on total number of characters in the file
//******************************************************************

#include <fstream>
#include <iostream>
#include <iomanip>
#include <cctype>

using namespace std;
int richUncle() // originally named main
{
// Prepare file for reading
ifstream text;
char character;

// Declare and initialize counters
int uppercaseCounter = 0;        // Number of uppercase letters
int lowercaseCounter = 0;        // Number of lowercase letters
int blankCounter = 0;            // Number of blanks
int digitCounter = 0;            // Number of digits
int punctuationCounter = 0;      // Number of end ‘.’, ‘?’, ‘!’
int allElseCounter = 0;          // Remaining characters

string inFileName;      // User specified input file name
cout << “Enter the name of the file to be processed” << endl;
cin >> inFileName;
text.open(inFileName.c_str());
if (!text)
{
cout << “Files did not open successfully.” << endl;
return 1;
}
text.get(character);             // Input one character
do
{

// Process each character
if (isupper(character))
uppercaseCounter++;
else if (islower(character))
lowercaseCounter++;
else if (isdigit(character))
digitCounter++;
else
switch (character)
{
case ‘ ‘ : blankCounter++;
break;
case ‘.’ :
case ‘?’ :
case ‘!’ : punctuationCounter++;
break;
defualt  : allElseCounter++;
break;

}
text.get(character);
} while (text);

// Calculate total number of characters
float total = uppercaseCounter + lowercaseCounter
+ blankCounter + digitCounter + punctuationCounter
+ allElseCounter;
cout << “Analysis of characters on input file ” << inFileName
<< endl;

// Write output on standard output device
cout << fixed << setprecision(3)
<< “Percentage of uppercase characters: “
<< uppercaseCounter / total * 100 << endl;
cout << fixed << setprecision(3)
<< “Percentage of lowercase characters: “
<< lowercaseCounter / total * 100 << endl;
cout << fixed << setprecision(3) << “Percentage of blanks: “
<< blankCounter / total * 100 << endl;
cout << fixed << setprecision(3) << “Percentage of digits: “
<< digitCounter / total * 100 << endl;
cout << fixed << setprecision(3) << “Percentage of end-of-sentence “
<< “punctuation ” << punctuationCounter / total * 100 << endl;
text.close();
// return 0; // removed as no longer main
}

 

Problem set 3: Lab 9-6 Case Study Maintenance

Requirements:
Exercise 1:
Compile and run an existing program using data of your choice.
Exercise 2:
Enhance the program to meet a specific set of requirements.

The biggest problem of this problem set, came as a result of having to add an additional function to existing code.

The additional function must meet the following requirements.
Requirements:
For each person, print the number of high-risk categories into which that individual falls. Compile and run the program with sufficient data to check that each combination of high-risk categories is represented.

Here is the original code:

//******************************************************************
// Profile Program
// This program inputs a name, weight, height, blood pressure
// readings, and cholesterol values.  Appropriate health messages
// are written for each of the input values on file healthProfile.
//******************************************************************

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

using namespace std;

// Function prototypes
string Name();
// This function inputs a name and returns it in first,
// middle initial, and last order

void EvaluateCholesterol(ofstream& healthProfile, string name);
// This function inputs HDL (good cholesterol) and LDL (bad
// cholesterol) and prints out a  health message based on their
// values on file healthProfile.
// Pre: Input file has been successfully opened

void EvaluateBMI(ofstream& healthProfile, string name);
// This function inputs weight in pounds and height in inches and
// calculates the body mass index (BMI prints a health message
// based on the BMI. Input in English weights.
// Pre: Input file has been successfully opened

void EvaluateBloodPressure(ofstream& healthProfile, string name);
// This function gets blood pressure readings (systolic/diastolic)
// and prints out a  health message based on their values
// on file healthProfile.
// Pre: Input file has been successfully opened

int main()
{
// Declare and open the output file
ofstream healthProfile;
healthProfile.open(“Profile”);
string name;
name = Name();

// Write patient’s name on output file
healthProfile << “Patient’s name ” << name << endl;

// Evaluate the patient’s statistics
EvaluateCholesterol(healthProfile, name);
EvaluateBMI(healthProfile, name);
EvaluateBloodPressure(healthProfile, name);
healthProfile << endl;

healthProfile.close();
return 0;
}

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

string Name()
// This function inputs a name and returns it in first,
// middle initial, and last order
{
// Declare the patient’s name
string firstName;
string lastName;
char middleInitial;

// Prompt for and enter the patient’s name
cout << “Enter the patient’s first name: “;
cin >> firstName;
cout << “Enter the patient’s last name: “;
cin >> lastName;
cout << “Enter the patient’s middle initial: “;
cin >> middleInitial;
return firstName + ‘ ‘  + middleInitial + “. ” + lastName;
}

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

void EvaluateCholesterol(ofstream& healthProfile, string name)
// This function inputs HDL (good cholesterol) and LDL (bad
// cholesterol) and prints out a  health message based on their
// values on file healthProfile.
{
int HDL;
int LDL;

// Prompt for and enter HDL and LDL
cout << “Enter HDL for ” << name << “: “;
cin >> HDL;
cout << “Enter LDL for ” << name << “: “;
cin >> LDL;
float ratio = (float)HDL/(float)LDL; // Calculate ratio of HDL to LDL

healthProfile << “Cholesterol Profile ” << endl
<< ”   HDL: ” << HDL << ”  LDL: ” << LDL << endl
<< ”   Ratio: ” << fixed << setprecision(4)
<< ratio << endl;

// Print message based on HDL value
if (HDL < 40)
healthProfile << ”   HDL is too low” << endl;
else if (HDL < 60)
healthProfile << ”   HDL is okay” << endl;
else
healthProfile << ”   HDL is excellent” << endl;
// Print message based on LDL value
if (LDL < 100)
healthProfile << ”   LDL is optimal” << endl;
else if (LDL < 130)
healthProfile << ”   LDL is near optimal” << endl;
else if (LDL < 160)
healthProfile << ”   LDL is borderline high” << endl;
else if (LDL < 190)
healthProfile << ”   LDL is high” << endl;
else
healthProfile << ”   LDL is very high” << endl;

if (ratio > 0.3)
healthProfile << ”   Ratio of HDL to LDL is good”
<< endl;
else
healthProfile << ”   Ratio of HDL to LDL is not good”
<< endl;
}

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

void EvaluateBMI(ofstream& healthProfile, string name )
// This function inputs weight in pounds and height in inches and
// calculates the body mass index Input in English weights.
{
const int BMI_CONSTANT = 703;  // Constant in English formula
int pounds;
int inches;

// Enter the patient’s weight and height
cout << “Enter the weight in pounds for ” << name << “: “;
cin >> pounds;
cout << “Enter the height in inches for ” << name << “: “;
cin >> inches;
int bodyMassIndex = pounds * BMI_CONSTANT / (inches * inches);

healthProfile << “Body Mass Index Profile” << endl
<< ”   Weight: ” << pounds << ”  Height: “
<< inches << endl;
// Print bodyMassIndex
healthProfile << ”   Body mass index is ” << bodyMassIndex
<< endl;
healthProfile << ”   Interpretation of BMI ” << endl;

// Print interpretation of BMI
if (bodyMassIndex <20)
healthProfile << ”   Underweight”
<< endl;
else if (bodyMassIndex <=25)
healthProfile << ”   Normal”  << endl;
else if (bodyMassIndex <= 30)
healthProfile << ”   Overweight”
<< endl;
else
healthProfile << ”   Obese”
<< endl;
}

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

void EvaluateBloodPressure(ofstream& healthProfile, string name)
// This function gets blood pressure readings (systolic/diastolic)
// and prints out a  health message based on their values
// on file healthProfile.
{
// Declare the blood pressure readings
int systolic;
int diastolic;

// Enter the patient’s blood pressure readings
cout << “Enter the systolic blood pressure reading for “
<< name << “: “;
cin >> systolic;
cout << “Enter the diastolic blood pressure reading for “
<< name << “: “;
cin >> diastolic;

// Print interpretation of systolic reading
healthProfile << “Blood Pressure Profile ” << endl
<< ”   Systolic: ” << systolic
<< ”   Diastolic: ” << diastolic << endl;
if (systolic < 120)
healthProfile << ”   Systolic reading is optimal” << endl;
else if (systolic < 130)
healthProfile << ”   Systolic reading is normal” << endl;
else if (systolic < 140)
healthProfile << ”   Systolic reading is high normal”
<< endl;
else if (systolic < 160)
healthProfile <<
”   Systolic indicates hypertension Stage 1″ << endl;
else if (systolic < 180)
healthProfile <<
”   Systolic indicates hypertension Stage 2″ << endl;
else
healthProfile <<
”   Systolic indicates hypertension Stage 3″ << endl;

// Print interpretation of diastolic reading
if (diastolic < 80)
healthProfile << ”   Diastolic reading is optimal” << endl;
else if (diastolic < 85)
healthProfile << ”   Diastolic reading is normal” << endl;
else if (diastolic < 90)
healthProfile << ”   Diastolic reading is high normal”
<< endl;
else if (diastolic < 100)
healthProfile <<
”   Diastolic indicates hypertension Stage 1″ << endl;
else if (diastolic < 110)
healthProfile <<
”   Diastolic indicates hypertension Stage 2″ << endl;
else
healthProfile <<
”   Diastolic indicates hypertension Stage 3″ << endl;
}

0
  Related Posts