Schedule‎ > ‎

Assignment 4: Making Selections

Objectives

  • Continue using if-statements to make selections
  • Start using logical operators to create more complex test conditions
  • Start using simple loops


Academic Honesty

Read the Scholastic Honesty Policy and Assignment Integrity policies of the syllabus. Here are some clarifications for this particular assignment:

  • Most importantly,  you undermine your own self confidence when you cheat,  because you know you didn't accomplish the assignment without cheating.
  • You may not show your completed code to another person or look at another person's code until you complete and submit this assignment and the due date has passed, except for code you develop together with your pair-programming partner.
  • You may get help from other people if you get stuck, but only if they do not show or tell you the code to type.
  • Remember that the instructor performs similarity tests on programming project submissions, and plagiarized code is usually very easy to detect.


Grading Criteria (30 pts + Extra Credit 2 pts)

For each part: 10 pts: Header Comment 1pt, Compiles 2 pts, Proper Formatting 1 pt, Works as Specified 6 pts

  1. tirelogic.cpp (10 pts)
  2. drought.cpp (10 pts)
  3. firstlast.cpp (10 pts)
  4. Extra Credit:  xcfirstlast.cpp (2 pts)

Total possible: 30, plus extra credit

..................................................................................................................................................................................................................................

Project Specifications

Your solutions to these projects must only use techniques we have covered so far.

Programming Style

For all programs, remember to follow all the style rules we have covered including the recent items:

  1. No magic numbers
  2. Indentation in while statements and placement of curly braces
  3. No tab characters in your code.

    You can remove tab characters by either setting up your text editor correctly (see here) or by running a program named astyle (see here).

  4. Meaningful variable names and consistent naming style (caps vs. underbars).





tire pressure information label

Project 1: Tire Pressure Logic

Tires must be properly inflated to achieve maximum handling, traction, and durability. It is the air pressure that supports the weight of your vehicle, not the tire itself. Tire pressure should be monitored frequently for safe driving and optimal tire performance.                                                                                                                                                                                                                                        Image source

Uneven pressure side to side can cause a pull to one side or the other. Thus we want to make sure that tire pressure is even from one side to another on both front and back as well as meeting minimum and maximum standards.

Ideally, just inflate all tires to the recommended pressure to prevent problems. Federal law requires car manufacturers to post tire pressure information on the doorwell of the driver's side, like the one shown in the image.

Project Specifications
  1. Start by copying this worksheet and saving it as tirelogic.cpp
  2. Add your name and the date to the file comment block at the top of the file.  There will be compiler warnings when you compile this code because you haven't yet used the variables declared at the top of the file.  Ignore these warnings for now.
  3. Compile your starting code to make sure it compiles.  Ignore the warnings for now.  Do not ignore any errors.  
  4. User input is already coded into the worksheet.

    Do not add any other input commands or change the input order.

  5. Complete each of the following steps and code your solutions into the worksheet where indicated by the comments. See the Example Run to verify the correctness of each computation.
    1. For each tire, write code to test and report on the inflation pressure using the words "Perfect", "Low", "High", or "OK", and based on the following criteria.
      • Perfect: Tire matches the recommended pressure PSI_FRONT or PSI_REAR exactly.
      • Low: Tire pressure is lower than the recommended pressure by the LIMIT.  Example:  28psi is Low for front tires
      • High: Tire pressure is higher than the recommended pressure by the LIMIT. Example:  36psi is High for front tires 
      • OK: Tire pressure is acceptable but not too low, too high or perfect.   Example:  30psi is OK for front tires
    2. Next compare the side-to-side pressure for both the front and rear tires. The front and rear comparison of side-to-side pressure are independent of each other. If the tires are more than LIMIT apart, report the pressure as "Uneven". If the pressure is not uneven, report the side-to-side pressure as "OK".  Example:  if right front is 30 and left front is 35 pressure is UNEVEN.
    3. Report on the overall inflation status such that if all measurements are acceptable, report the overall tire inflation as "OK". Otherwise, report the overall tire inflation as "BAD".
    4. To report the overall status, use the boolean variable goodPressure which is initialized to true. When a tire pressure problem is found, assign false to goodPressure.
  6. Example Run: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
    *** Tire Logic ***
    Input 32 36 32 35 for values in parentheses.
    
    Enter tire pressures when prompted.
    Input right front pressure: 32
    Input left front pressure: 33
    Input right rear pressure: 34
    Input left rear pressure: 35
    
    *** Checking each tire's pressure ***
    Right front 32 (Perfect): Perfect
    Left front 33 (High): OK
    Right rear 34 (Low): OK
    Left rear 35 (OK): OK
    
    *** Comparing side to side pressure ***
    Front pressure comparison (Uneven): OK
    Rear pressure comparison (OK): OK
    
    *** Overall Status ***
    Tire inflation (BAD): OK
    

    In the above example run, the user entered the values shown in red italics (for emphasis) to produce the output. Your program does NOT print the characters in red italics, nor does the user input appear in red italics. The values in (parentheses) are expected values when entering the suggested input of: 32 36 32 35.

  7. Test your program with other inputs to exercise each and every if else statement.  One example test:  36 29 36 36

  8. After displaying the output, exit the program.
  9. Submit the source code file tirelogic.cpp with the rest of  the programs to Canvas Assignment 4.
References and More Information
  1. How tire inflation affects performance
  2. The Effect of Tire Pressure on Fuel Economy


Drought Severity Levels [3]
LevelIntensity% of Mean
D0Abnormally Dry41-60%
D1Moderate Drought21-40%
D2Severe Drought11-20%
D3Extreme Drought5-10%
D4Exceptional Drought1-4%

Project 2: Drought Conditions

A drought is a period of below average rainfall resulting in water shortages. The United States Drought Monitor measures drought conditions in the US every week and publishes the severity using classifications like those in the table to the right. Currently, 81.7% of California is in a drought condition.

In this project we state the severity of the drought using the categories supplied by the United States Drought Monitor as shown in the table to the right.

For reference, the following table is the currently known rainfall data for the Santa Cruz area in Water Year (WY) 2018. Notice that water year starts in October of the previous year.

Santa Cruz Rainfall in Inches
OctNovDecJanFebMarAprMayJunJulAugSep
Historical Average 1.444.084.226.496.154.781.970.700.180.140.110.41
Cumulative Average1.445.529.7416.2322.3827.1629.1329.8330.0130.1530.2630.67
Water Year 2018 0.072.750.185.29        
Cumulative WY 20180.072.823.008.29        
Project Specifications
  1. Write a program that asks the user for the historical average rainfall year-to-date (YTD) and the current water year (WY) rainfall YTD for a given area. From this data, calculate if the area is potentially in a drought and report the severity of the drought using the classifications shown in the Drought Severity Levels table above.
  2. Name the source code file drought.cpp and include all your code in this single file.
  3. Ask the user for the average rainfall year-to-date (YTD) followed by the current rainfall YTD. The input from the user must be in this order as shown in the Example Run. Assume the user inputs only valid data.
  4. After the user inputs the data, calculate the current rainfall (cc) divided by the average rainfall (aa), and display the result as a percentage using the following formula and in the format shown in the Example Run.

    pct = c / a * 100

  5. From the percentage (pctpct), write a series of if-else statements to display the intensity of the current year rainfall with the wording from the intensity column of the Drought Severity Levels table above. If there is no drought, print the water year intensity as: normal rainfall year.
  6. Example Run: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
    *** Drought Monitor ***
    
    Average rainfall YTD: 16.23
    Current rainfall YTD: 17
    Rainfall of 17 is 104.744% of the average of 16.23 inches.
    Water year intensity: normal rainfall.
    Run again? (y/n) y
    
    Average rainfall YTD: 16.23
    Current rainfall YTD: 8.29
    Rainfall of 8.29 is 51.0783% of the average of 16.23 inches.
    Water year intensity: abnormally dry.
    Run again? (y/n) n
    

    In the above example run, the user entered the values shown in red italics (for emphasis) to produce the output. Your program does NOT print the characters in red italics, nor does the user input appear in red italics.

  7. Add a while statement that allows the user to repeat the program by inputting a "y" (without the quotes), and exiting the loop for any other character entered, as shown in the Example Run.
  8. Test your program with a variety of inputs,  you want to test each path through your code.
  9. Submit the source code file drought.cpp with the rest of the assignment in Canvas Assignment 4.
References and More Information
  1. Drought: Wikipedia article.
  2. United States Drought Monitor: California Data
  3. How are the drought categories assigned?: United States Drought Monitor Tutorial
  4. Historic Average: Santa Cruz, California: Intellicast
  5. Monthly Precipitation Summary Water Year 2018: California Nevada River Forecast Center: NOAA
  6. Monthly Climate Summary Santa Cruz, California: Western Regional Climate Center historical data, 1948 to 2005


Hello!
012345

Project 3: Comparing Characters

Remember from lesson 3.2.6 that the substr() function can extract one or more characters from a string. Also recall from lesson 3.3.3, that we may compare string characters to each other because they are stored as numbers in the computer. The characters of the alphabet are arranged in numerical order using this ASCII table.

In this project, we use the substr() function to extract characters from a string. Once we extract the characters, we use relational operators to test if the first or last character of a string is earlier in the alphabet.

Project Specifications
  1. Write a program that tests if the first or last letter of a word is earlier in the alphabet. If the characters are the same, we note that as well.
  2. Name the source code file firstlast.cpp and include all your code in this single file.


  3. Ask the user for the following inputs (and no other input) in this order and each on their own line, as shown in the Example Run below:
    1. a word such as "easy" (without the quote marks) as a string (the user must input an all lowercase string).
    2. "y" or "n" (without the quote marks) to see if the program should loop again

    Assume the user enters only valid data and all lowercase.

  4. Use substr() to test if the first or last letter of the word input by the user is earlier in the alphabet and print Last or First followed by the letter itself inside of double quotes. See the Example Run for the exact format.
  5. If the letters are the same then print, "First and last characters are the same." (without the quotes) as shown in the Example Run.
  6. Example Run: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
    *** Comparing First and Last Characters ***
    
    Input a word (all lowercase): easy
    First letter "e" is earlier in the alphabet.
    Run again? (y/n) y
    
    Input a word (all lowercase): zebra
    Last letter "a" is earlier in the alphabet.
    Run again? (y/n) y
    
    Input a word (all lowercase): roar
    First and last characters are the same.
    Run again? (y/n) y
    
    Input a word (all lowercase): a
    First and last characters are the same.
    Run again? (y/n) y
    
    Input a word (all lowercase): apple
    First letter "a" is earlier in the alphabet.
    Run again? (y/n) n
    

    In the above example run, the user entered the values shown in red italics (for emphasis) to produce the output. Your program does NOT print the characters in red italics, nor does the user input appear in red italics.

  7. Add a while statement that allows the user to repeat the program by inputting a "y" (without the quotes), and exiting the loop for any other character entered, as shown in the Example Run.
  8. Submit the source code file firstlast.cpp with the rest of Assignment 4 in Canvas.


Extra Credit

The following are worth extra credit points:

  1. Complete the firstlast.cpp program with 3 or fewer relational expressions, including the while loop, and without using techniques we have not covered. (2 points). You must submit this as xcfirstlast.cpp to receive extra credit.

SOLUTION CODE:

Project 1:  tirelogic.cpp

/**

    CS-11 Asn 4, tirelogic.cpp

    Purpose: Report on the condition of tires on a car.


    @author Sharon Strelitz

    @version 1.0 Feb. 10, 2018

*/

#include <iostream>

#include <cmath>

using namespace std;


int main() {

    // Do NOT change the next few lines

    const int PSI_FRONT = 32;

    const int PSI_REAR = 36;

    const int LIMIT = 3;

    bool goodPressure = true; // optimistic

    int rightFront, leftFront, rightRear, leftRear;

    cout << "*** Tire Logic ***";

    cout << "\nInput 32 36 32 35 for values in parentheses.\n";

    // Make changes after this line as stated in instructions and comments.


    // Prompt user and get 4 tire pressures, in order shown for Example Run

    cout << "Input right front pressure: ";

    cin >> rightFront;

    cout << "Input left front pressure: ";

    cin >> leftFront;

    cout << "Input right rear pressure: ";

    cin >> rightRear;

    cout << "Input left rear pressure: ";

    cin >> leftRear;


    cout << "\n*** Checking each tire's pressure ***\n";

    // For each tire say whether Perfect, Low, High, OK


         

    // Add if tests for right front tire; cout Perfect, Low, High, OK

    // If not OK or Perfect, set goodPressure = false.

    cout << "Right front " << rightFront << " (Perfect): ";

    if (rightFront > PSI_FRONT + LIMIT) {

        cout << "High";

        goodPressure = false;

    }  else if (rightFront < PSI_FRONT - LIMIT) {

        cout << "Low";

        goodPressure = false;

    }  else if (rightFront == PSI_FRONT) {

        cout << "Perfect";

    }  else  {

        cout << "OK";

    }

    cout << "\nLeft front " << leftFront << " (High): ";


    // Add if tests for left front tire; cout Perfect, Low, High, OK

    // If not OK or Perfect, set goodPressure = false.

     if (leftFront > PSI_FRONT + LIMIT) {

        cout << "High";

        goodPressure = false;

    }  else if (leftFront < PSI_FRONT - LIMIT) {

        cout << "Low";

        goodPressure = false;

    }  else if (leftFront == PSI_FRONT) {

        cout << "Perfect";

    }  else  {

        cout << "OK";

    }


    cout << "\nRight rear " << rightRear << " (Low): ";

    // Add if tests for right rear tire; cout Perfect, Low, High, OK

    // If not OK or Perfect, set goodPressure = false.

    if (rightRear > PSI_REAR + LIMIT) {

        cout << "High";

        goodPressure = false;

    }  else if (rightRear < PSI_REAR - LIMIT) {

        cout << "Low";

        goodPressure = false;

    }  else if (rightRear == PSI_REAR) {

        cout << "Perfect";

    }  else  {

        cout << "OK";

    }

    cout << "\nLeft rear " << leftRear << " (OK): ";

    // Add if tests for left rear tire; cout Perfect, Low, High, OK

    // If not OK or Perfect, set goodPressure = false.

    if (leftRear > PSI_REAR + LIMIT) {

        cout << "High";

        goodPressure = false;

    }  else if (leftRear < PSI_REAR - LIMIT) {

        cout << "Low";

        goodPressure = false;

    }  else if (leftRear == PSI_REAR) {

        cout << "Perfect";

    }  else  {

        cout << "OK";

    }


    cout << "\n\n*** Comparing side to side pressure ***\n";

    // Compare both front and both rear

    // Add if tests to compare left and right front; cout OK, Uneven

    // If not OK , set goodPressure = false.

    cout << "Front pressure comparison (Uneven): ";

    if (abs(leftFront - rightFront) > LIMIT) {

        cout << "Uneven";

        goodPressure = false;

    }  else  {

        cout << "OK";

    }

 

    cout << "\nRear pressure comparison (OK): ";

    // Add if tests to compare left and right rear; cout OK, Uneven

    // If not OK , set goodPressure = false.

    if (abs(leftRear - rightRear) > LIMIT) {

        cout << "Uneven";

        goodPressure = false;

    }  else  {

        cout << "OK";

    }


    cout << "\n\n*** Overall Status ***\n";

    // Add if test to state overall status by testing goodPressure

    cout << "Tire inflation (BAD): ";

    if (goodPressure)  {

        cout << "OK";

    }  else  {

        cout << "BAD";

    }

        

    cout << endl;


    return 0;

}







Project 2: drought.cpp
/**
    CS-11 Asn 4, drought.cpp
    Purpose: Report on Drought Severity Levels.

    @author Sharon Strelitz
    @version 1.0 Feb. 10, 2018
*/
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    // Do NOT change the next few lines
    const int D0 = 60;
    const int D1 = 40;
    const int D2 = 20;
    const int D3 = 10;
    const int D4 = 4;
    double averageRainfallYTD = 0.0, currentRainfallYTD = 0.0;
    double percentage = 0.0;
    string runAgain = "y";
    cout << "*** Drought Monitor ***" << endl << endl;
    while (runAgain == "y")  {
        cout << "Average rainfall YTD: ";
        cin >> averageRainfallYTD;
        cout << "Current rainfall YTD: ";
        cin >> currentRainfallYTD;
        percentage = currentRainfallYTD/averageRainfallYTD * 100;
        cout << "Rainfall of " << currentRainfallYTD << " is "
             << percentage
             << "% of the average of " << averageRainfallYTD << " inches." << endl; 
        cout << "Water year intensity: "; 
        if (percentage > D0)  {
            cout << "normal rainfall" << endl;
        } else if (percentage > D1) {
            cout << "Abnormally Dry" << endl;
        } else if (percentage > D2) {
            cout << "Moderate Drought" << endl;
        } else if (percentage > D3) {
            cout << "Severe Drought" << endl;
        } else if (percentage > D4) {
            cout << "Extreme Drought" << endl;
        } else {
            cout << "Exceptional Drought" << endl;
        }  
        cout << "Run again? (y/n) ";
        cin >> runAgain;
        cout << endl;
    }
    return 0;
}
Project 3:  xcfirstlast.cpp
/**
    CS-11 Asn 4, firstlast.cpp
    Purpose: Extract and Compare First and Last characters of a word.

    @author Sharon Strelitz
    @version 1.0 Feb. 10, 2018
*/
#include <iostream>
using namespace std;

int main() {

    string word = "", runAgain = "y";
    string firstChar = "", lastChar = "";
    cout << "*** Comparing First and Last Characters ***" << endl << endl;
    while ("y" == runAgain)  {
        cout << "Input a word (all lowercase): ";
        cin >> word;
        firstChar = word.substr(0,1);
        lastChar = word.substr(word.length() - 1,1);
        if (firstChar < lastChar) {
            cout << "First letter \"" << firstChar << "\" is earlier in the alphabet" << endl;
        }  else  if (firstChar > lastChar) {
            cout << "Last letter \"" << lastChar << "\" is earlier in the alphabet" << endl;
        }  else {
            cout << "First and last characters are the same." << endl; 
        }
        cout << "Run again? (y/n) ";
        cin >> runAgain;
        cout << endl;
    }
    return 0;
}

Subpages (2): ascii_table tirelogic.cpp
Comments