A7-Programs With Functions

Table of Contents


Objectives

  • Use a loop to iterate over all the characters in a string
  • Write simple functions
  • Use parameters to send data to functions.
  • Code return statements to return values from functions
  • Start to use functions to organize program code

Academic Honesty

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

  • You are encouraged to work with one other student of this class following the rules of Pair Programming for Homework Assignments. If you choose to pair program, there is a bonus applied.
  • You may not give a copy of your code to your designated pair-programming partner if you did not develop the code together.
  • You may not look at another student's code until you complete and submit this assignment, except for code you develop code together with your pair-programming partner.
  • You may get help from people other than your pair-programming partner 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 copied or plagiarized code is usually very easy to detect.

Preparation

  1. Make sure you have completed the exercises from lesson 7.
  2. Complete the Review Exercises in CodeLab 7. These exercises will help prepare you for the problem-solving programs and should be completed first.

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 covered including the recent items:

  1. Avoid duplicating code (see textbook page 208)
  2. Function naming conventions (See: Function Names)
  3. Indentation in functions and placement of curly braces (See: Indentation)
  4. No magic numbers. (Hint: make arrays of numbers const)
  5. Indentation in while statements and placement of curly braces
  6. No tab characters in your code.

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

  7. Meaningful variable names and consistent naming style (caps vs. underbars).
  8. Create the README.txt file following the instructions.

Image

Project 1: Function Worksheet

Functions are an important part of programming, allowing us to break up long sequences of code into shorter reusable parts. We then assemble the parts to create larger programs.

In this project we complete several functions. Each function is like a smaller program inside of a our larger program. Notice that we can focus on each function separately, allowing our full attention on each part of the problem.

Project Specifications
  1. Start by downloading the worksheet: funwork.cpp.

    Keep the same filename and add to the existing code to complete the project. Leave the existing code unchanged, except where instructed in comments.

  2. Add your name and the date to the file comment block at the top of the file.
  3. No user input is required for this project and do not add any.
  4. Write the required functions, one per problem, as described by the function declaration and comment block.

    Do NOT change any of the function declarations and do NOT make any changes to the main() function besides uncommenting code where stated in comments.

  5. Do not turn in code with cout in any function besides the cout statements already coded in main().

    You may add cout statements to debug code but must remove them before turning in your code.

  6. Compile and run the code when finished with each function to see to verify correctness. Check the test results and make any alterations to your functions as necessary.

    You may see warnings when compiling. Remember that code with warnings does compile but the warning is giving you hints about problems with the code.

  7. Example Run: The outputs of the program must look exactly like the following for full credit, including the same order and format of the output. The exception is that the random numbers will change every time you run the program.
    *** Function Worksheet! ***
    
    *** Testing divTrouble ***
    divTrouble(2, 3) must be (0): 0
    divTrouble(3, 2) must be (1): 1
    divTrouble(2, 1) must be (2): 2
    divTrouble(1, 0) must be (0): 0
    
    *** Testing isWeekend ***
    isWeekend(1) must be (true): true
    isWeekend(7) must be (true): true
    isWeekend(0) must be (false): false
    isWeekend(2) must be (false): false
    
    *** Testing is42 ***
    is42(42, 4) must be (true): true
    is42(4, 42) must be (true): true
    is42(41, 1) must be (true): true
    is42(4, 2) must be (false): false
    
    *** Testing firstDigit ***
    firstDigit("abc123") must be (3): 3
    firstDigit("a3bc2d") must be (1): 1
    firstDigit("abcde") must be (-1): -1
    firstDigit("") must be (-1): -1
    
    *** Testing arrayEven ***
    arrayEven([1], 1) must be (1): 1
    arrayEven([1, 2], 2) must be (1): 1
    arrayEven([1, 2, 3], 3) must be (4): 4
    arrayEven([1, 2, 3, 4], 4) must be (4): 4
    
    *** End of Tests ***
    
  8. When all of the tests pass, and your code compiles without warnings, upload your completed source code file with the rest of the assignment as described in Deliverables.

2014 Checy Volt Car Sticker
Image source

Project 2: Car Travel Cost with Functions

In this project we update our carcost.cpp program from assignment 2 to use functions.

As we saw in assignment 2, gas and electric powered cars have different efficiencies in their use of energy. Electric engines have much higher efficiencies and thus have much higher fuel economy ratings.

Batteries for EVs are designed for extended life and a study [3] by the US Department of Energy suggest these batteries may last 12 to 15 years in moderate climates and 8 to 12 years in severe climates.

Project Specifications
  1. Update your car travel programs from previous assignments to use functions, correcting any errors you made in the prior programs. If you are pair programming then you may combine the previous work of the two partners in a suitable way.
  2. Name the source code file for this project carcostfun.cpp and include all your code in this file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. Ask the user for the following inputs (and no other input) in this order, as shown in the Example Run below:
    1. Efficiency of the gas powered car in miles per gallon (MPG)
    2. Price of a gallon of gas
    3. Efficiency of the electric car in miles per gallon equivalent (MPGe)
    4. Price of a kilowatt-hour (kWh) of electricity
  4. The program must define the following functions and each function must be called at least once:
    1. cost100Gas or cost_100_gas: this function takes two numerical parameters, the MPG of a car and the cost of a gallon of gas, returning the cost of traveling 100 miles.
    2. cost100Elec or cost_100_elec: this function takes two numerical parameters, the MPGe of an electric car and the cost of one kilowatt hour (kWh) of electricity, returning the cost of traveling 100 miles

    Use these function names exactly.

  5. Get the input and show the output in the main() function. Call the other functions to compute the costs.
  6. Output the cost of travel by rounding the cost to the nearest cent.

    Hint: see lesson 4.1.3: Decimal Formatting.

  7. 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.
    Gas vs. Electric Car Travel Comparison
    
    Enter the fuel efficiency of the gas car in MPG: 24.7
    Enter the cost of one gallon of gas: 2.89
    Cost of traveling 100 miles in a gas car is $11.70
    
    Enter the energy efficiency of electric car in MPGe: 112
    Enter the cost of one KWH of electricity: .12503
    Cost of traveling 100 miles in an electric car is $3.76
    
    Gas vs. Electric Car Travel Comparison
    
    Enter the fuel efficiency of the gas car in MPG: 50
    Enter the cost of one gallon of gas: 2.97
    Cost of traveling 100 miles in a gas car is $5.94
    
    Enter the energy efficiency of electric car in MPGe: 123
    Enter the cost of one KWH of electricity: .12225
    Cost of traveling 100 miles in an electric car is $3.35
    

    In the above example runs, the user entered the values shown in aqua italics (for emphasis) to produce the output. Your program does NOT print the characters in aqua italics, nor does the user input appear in aqua italics. Note that the MPGe of 112 is for a Nissan Leaf and the 123 is for a Tesla Model 3.

  8. After displaying the output, exit the program.
  9. Submit this project with the rest of the assignment as described in Deliverables.
References and More Information
  1. Electric Schedule EV: $0.12503 effective March 1, 2017 (retrieved 01/10/2019)
  2. All-Electric Vehicles: why electric vehicles are more efficient from the official U.S. government source for fuel economy information.
  3. Battery Life: electric car batteries are designed for long life, unlike batteries in most phones and computers.

Image
Image source

Project 3: Data Visualization

In this project, we will create a general data visualization tool that can generate bar graphs for a variety of data sets. As an example data set, we will use the following data on CO2 emissions.

2015 CO2 Emissions in Millions of Metric Tons
Country China USA India Russia Japan Germany S.Korea Iran Canada
CO2 Emissions [1] 9041 4998 2066 1469 1142 730 586 553 549

We will save the above data in arrays and use the arrays as a database for accessing the data.

Project Specifications
  1. Write a program that codes the above data for nine countries, CO2 emissions and country names, into arrays and draws a bar graph for the top data items as requested by the user.
  2. Name the source code file dataviz.cpp and include all your code in this single file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. Inside the main() function, ask the user how many data items to display.

    No other user input is required for this project and do not add any.

  4. Write one and only one function, besides main(), using the following starter code:
    /**
        On a single line, displays the following information: label, data,
        bar graph of data.
    
        @param label The name of the data item
        @param data The amount of the data item
        @param step The amount of data per asterisk
        @return number of stars
    */
    int drawBar(string label, double data, double step)
    {
        int numStars = data / step;
        // display label and data
        // for loop to draw bar
        return numStars;
    }
    

    Call the function from main(). Do not delete or change any existing code except comments as desired. Notice and make use of the variable numStars. You may, of course, add more coding statements.

  5. Inside the drawBar() function, display all the following data on one line:
    1. country name
    2. CO2 emissions in millions of metric tons
    3. a bar showing the relative emissions.
    For example, here is the bar graph for the USA:
    USA       4998 ***********************************
    

    Separate the country name, CO2 emissions, and bars by spaces and not tabs as shown above.

  6. Call drawBar() from main(), save each value returned in a variable, find the shortest bar using the minimum value algorithm from lesson 5.3.4, and print a message about the number of stars for the shortest bar as shown in the Example Runs.
  7. The longest bar (number of asterisks) must always be 64 exactly and leave one space before the right edge of an 80 column terminal. Thus no line may be longer than 79 characters including spaces.
  8. Example Runs: The outputs of the program must look exactly like the following for full credit, including the same order and format of the output. Notice how the columns line up. Use spaces (' ') and NOT tabs ('\t') for alignment.
    Enter number of items to display: 3
    
                 CO2 Emissions by Country in Millions of Metric Tons
    China     9041 ****************************************************************
    USA       4998 ***********************************
    India     2066 **************
     * = 141 million metric tons
    Shortest bar is 14 *'s
    
    Enter number of items to display: 9
    
                 CO2 Emissions by Country in Millions of Metric Tons
    China     9041 ****************************************************************
    USA       4998 ***********************************
    India     2066 **************
    Russia    1469 **********
    Japan     1142 ********
    Germany    730 *****
    S.Korea    586 ****
    Iran       553 ***
    Canada     549 ***
     * = 141 million metric tons
    Shortest bar is 3 *'s
    

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

  9. Submit the source code file dataviz.cpp with the rest of the assignment as described in Deliverables.
Hints:
References and More Information
  1. Each Country's Share of CO2 Emissions
  2. List of Countries by Population

Extra Credit

The following are worth extra credit points:

  1. Complete the assignment using pair programming with the same person. (2 points for all files)
  2. Add a correctly filled out function comment block for all functions besides main() in all three projects. (1 point)

    All projects must have functions besides main() for this extra credit.

  3. Create the correct spacing for each bar of the dataviz.cpp between the country and CO2 using the setw(), left and right formatting manipulators described on pages 49-51 (1/e: 53-55) of the textbook or here. (1 point)

    To use these manipulator, include the iomanip library. For credit, the dataviz.cpp program must compile and function well enough to produce correct output and you must use all three manipulators.

  4. Create your own interesting function problem for the function worksheet. (1 point for completing, 1 point for robust test cases, and 1 point for interest and creativity)
    1. Submit the extra function and its main() function in a file named xcfunwork.cpp.
    2. Do not have any user input in the extra credit file.
    3. Label the tests in main() with a cout statement with the words "Testing Extra Credit" followed by the function name, like:
      *** Testing Extra Credit myFabFun ***
      
    4. Following the label, include at least 3 test cases calling the extra function in main(), testing different results of the function call like the test cases do in the standard funwork2.cpp project.
    5. Be sure to credit the source of the extra function if we have not covered the idea or code in both the source code file and README.txt. If it is original work, then state how you came up with the idea.
  5. Make sure your program has no more than five (5) relational operators.

Make certain that your README.txt file describes any extra credit attempted.

Tutorial Lab

In preparation for next weeks lessons, complete the following:

  1. Read the assigned reading in the textbook
  2. Complete the Tutorial Exercises in CodeLab 7 before the specified due date.

    Refer to the assigned reading for the next lesson to help you understand the problems. Also, you can use the online lecture notes for more information as the notes become available. You can look at solutions if you miss your first few attempts and are stuck by clicking the "Solution" tab.

Grading Criteria

The instructor will evaluate your assignment using the following criteria. Thus you should check your assignment against these criteria to maximize your score.

Each criteria represents a specific achievement of your assignment and has a scoring guide. The scoring guide explains the possible scores you can receive. Some scoring guides have a list of indicators. These indicators are a sign of meeting, or a symptom of not meeting, the specific criterion. Note that a single indicator may not always be reliable or appropriate in a given context. However, as a group, they show the condition of meeting the criterion.

For information on grading policies, including interpretation of scores, see the syllabus.

Lesson Exercises

  • 2: All lesson exercises attempted and turned in
  • 1: Some lesson exercises completed and turned in
  • 0: No lesson exercises completed or turned in

Programming Projects (x3)

  • 5: Demonstrates mastery of the program
    • Applies concepts from the lessons appropriately
    • Meets all specifications (see above)
    • Runs to completion with no abnormal error conditions
    • Generates correct output given correct input
    • Correct file name
  • 4: Has most of the functionality expected of the program
    • Demonstrates some techniques from the lesson
    • Attempts to meet all but one of the specifications (see above)
    • Implementation seems more complicated than necessary.
    • May have one minor error
  • 3: Has some of the functionality expected of the program
    • Demonstrates some techniques from the lesson
    • Programs works correctly but did not use functions
    • Attempts to meet at least 1/2 of the specifications (see above)
    • Implementation seems excessively complicated.
    • May have 2-3 minor errors
  • 2: Serious functional problems but shows some effort and understanding
    • Attempts to meet less than 1/2 of the of the specifications (see above)
    • Has a major error or many minor errors
    • Implementation seems very convoluted
    • Demonstrates few techniques from the lesson
  • 1: Does not compile, minimal work, or wrong file turned in
  • 0: Not turned in or uses techniques not covered in the course so far.

Programming Projects Style

  • 3: Code is well-documented including:
  • 2: Code has a minor documentation error
  • 1: Code has some documentation errors
  • 0: No apparent attempt to follow documentation standards or write documentation comments

CodeLab and Other Tutorial Exercises

  • Number CodeLab completed correctly / number exercises * 8 and rounded up to the nearest integer.

README.txt File

  • 2: README.txt file submitted following the instructions
  • 1: README.txt file submitted but some information was missing
  • 0: No README.txt file submitted

Total possible: 30, plus extra credit

Deliverables

Submit your assignment to Canvas, in the assignment folder A7-Programs With Functions, following the instructions for submitting homework. Include the following items for grading:

  1. README.txt file
  2. All the exercise files from Lesson 7
  3. funwork.cpp
  4. carcostfun.cpp
  5. dataviz.cpp
  6. Optionally, xcfunwork.cpp (extra credit)

You must submit all the files needed to complete your assignment. Your assignment must work as submitted. Remember to test and double check your files before submitting them. If you make a mistake, you can resubmit up to the deadline. If you resubmit, you must include all your assignment files in the last submission as Canvas hides prior submissions.

Last Updated: April 26 2019 @15:46:41