A7-Programs With Functions

Table of Contents


Objectives

  • Use a loop to iterate over all the characters in a string
  • Test user input for errors
  • Write simple functions
  • Use parameters to send data to functions.
  • Code return statements to return values from functions
  • Use functions to organize program code
  • Look up data in arrays

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.

A main program with many functions

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. Also, points are taken off for warnings.

  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 fToC ***
    fToC(32) must be (0): 0
    fToC(212) must be (100): 100
    fToC(42) must be (5.55556): 5.55556
    fToC(70) must be (21.1111): 21.1111
    fToC(107.6) must be (42): 42
    
    *** Testing isDigit ***
    isDigit('0') must be (true): true
    isDigit('9') must be (true): true
    isDigit('5') must be (true): true
    isDigit('/') must be (false): false
    isDigit(':') must be (false): false
    
    *** Testing bool posNeg ***
    posNeg(1, -1) must be (true): true
    posNeg(-1, 1) must be (true): true
    posNeg(-1, -1) must be (false): false
    posNeg(1, 1) must be (false): false
    
    *** Testing countLower ***
    countLower("") must be (0): 0
    countLower("abc") must be (3): 3
    countLower("abCdeZ") must be (4): 4
    countLower("A3bc2def") must be (5): 5
    
    *** Testing removeLetter ***
    removeLetter("Alfa", 'a') must be (Alf): Alf
    removeLetter("3Kilo", 'K') must be (3ilo): 3ilo
    removeLetter("Zulu", 'u') must be (Zl): Zl
    removeLetter("Ajax2!", '2') must be (Ajax!): Ajax!
    removeLetter("zulu", 'x') must be (zulu): zulu
    
    *** 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.

Image
Image source: Mike Knuepfel

Project 2: Frequent Letters

The frequency of letters in text has been studied for use in cryptanalysis for centuries [1]. Letter frequency is also important in a number of other fields such as linguistics and data compression. The most frequent letters in English press reporting are ETAON [2].

Project Specifications
  1. Write a program that counts the number of occurrences of the five (5) most popular letters in the English alphabet: ETAON and their lowercase variants.
  2. Name the source code file letterfreq.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. Ask the user to enter a word or phrase, as shown in the Example Runs. Use a single getline() for the input.
  4. Write one, and only one, function besides main(), with the following header:
    /**
        Counts the number of letters.
        @param str a string with word or phrase
        @return the number of letters.
    */
    int frequentLetters(string str)
    
    1. The name of your function must be either frequent_letters() or frequentLetters() and the function must have one string parameter for a prompt. You may use any parameter name as long as the parameter type is string.
    2. When called, the function returns a count of the letters in the string parameter that match the most frequent letters in the English alphabet: ETAON and their lowercase variants.

    Do not code any cin or cout statements in this function. Do NOT change the function's name, parameter type, number of parameters, or return type. Instead, pay attention to the intent of these items to guide your code development.

  5. Call the function from main() and print the number returned from the function call as shown in the Example Runs.
  6. Example Runs: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and exact 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.
    ETAON Letter Analyzer
    
    Enter a word or phrase: aTone
    Your input contains 5 frequent letters.
    (End of program)
    
    ETAON Letter Analyzer
    
    Enter a word or phrase: Mary had a little lamb.
    Your input contains 7 frequent letters.
    (End of program)
    
    ETAON Letter Analyzer
    
    Enter a word or phrase: Three blind micE
    Your input contains 5 frequent letters.
    (End of program)
    

    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.

  7. After displaying the output, exit the program. Do NOT loop and run again.
  8. Submit this project with the rest of the assignment as described in Deliverables.
Hints:
  • Start with the Try It in 6.1.3: Iterating Strings and notice how the for-loop iterates through each letter of the input string.
  • Use if-statements to test for the letters in which we are interested. Then remember how we were able to count using a counter variable.
References and More Information
  1. Letter frequency: Wikipedia
  2. Letter Frequencies: letterfrequency.org

Image
Image source

Project 3: Weight on Other Planets Redux

In the planetary weight project from assignment 4, we saw that we could predict our weight on other planets based on our weight on Earth. However, the code the the conversion is fairly lengthy.

In this project, we redo our planetary weight project from assignment 4, Project 2 to minimize if-statements and relational operators by using arrays and loops. In addition, we package the decoding operation into a function and make the program easier to use.

Project Specifications
  1. Redo your planetary weight project from assignment 4 to use loops, arrays and functions, both correcting any prior errors made and extending the program as described below.

    If you are pair programming with a different partner than assignment 4 then you may start with the previous combined work of the two partners or the instructor's posted solution.

  2. Name the source code file weightfun.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. As before, 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. The weight in pounds (double)
    2. The name of the planet (string)

    Code all user input and output in the main() function.

  4. As before, include a while statement that allows the user to repeat the program by entering a 'y' (without the quotes).
  5. Write one and only one function, besides main(), with the following signature exactly:
    /**
        Converts a weight on Earth to a weight on another planet.
    
        @param weight The weight on Earth to convert.
        @param planet The name of the target planet for the weight.
        @return The weight on another planet or -1 for no match.
    */
    double weightConverter(double weight, string planet)
    

    Call the function from main(). When called, the function returns the weight on the planet parameter or -1 for no match.

    Do not code any cin or cout statements in this function. Do NOT change the function's name, parameter type, number of parameters, or return type. Instead, pay attention to the intent of these items to guide your code development.

  6. As before, the program must print the weight on another planet of the users choice using the following conversion factors:
    Planet Conversion Factor
    Mercury 0.38
    Venus 0.90
    Mars 0.38
    Jupiter 2.54
    Saturn 1.08
    Uranus 0.91
    Neptune 1.19

    Source: NASA [1]

  7. As an intermediate step, start by moving your weight conversion if-statements into the weightConverter() function and call the function from main(). Your program should still operate the same after this step.
  8. Next, revise the weightConverter() function by storing the planet names in an array of strings and the conversion factors in another array of doubles such that the indexes of the codes and names are the same. For example:
    const string NAMES[] = {"Mercury", "Venus",...};
    const double FACTORS[] = { 0.38, 0.90,... };
    

    Remember to declare your arrays constant as shown above.

  9. Use a for-loop to search each element of the CODES array and an if-statement to test if the code matches an element of the CODES array as shown in lesson 7.2.4: Finding Elements in an Array. Use the index of the found CODES element to look up the translated name in the NAMES array.
  10. Keep the number of your relational operators to less than or equal to seven (7) in the entire program and do not use any techniques we have not covered so far.
  11. 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 exact wording of the output. Prompts for user input may vary as long as the prompts end in a colon (:) or question mark (?), and the text has no other colons or question marks. For the input shown you must get the same output. However, the output must change correctly if the user inputs are different.
    Welcome to the Solar Planet Weight Converter!
    
    Enter your weight in pounds: 100
    Now, select from one of the following planets:
        Mercury
        Venus
        Mars
        Jupiter
        Saturn
        Uranus
        Neptune
    Please enter the planet: Mercury
    On Mercury you weigh 38.0 lbs.
    
    Do you want to run again? (y/n) y
    Enter your weight in pounds: 123
    Now, select from one of the following planets:
        Mercury
        Venus
        Mars
        Jupiter
        Saturn
        Uranus
        Neptune
    Please enter the planet: marz
    Invalid planet name.
    
    Do you want to run again? (y/n) y
    Enter your weight in pounds: 111
    Now, select from one of the following planets:
        Mercury
        Venus
        Mars
        Jupiter
        Saturn
        Uranus
        Neptune
    Please enter the planet: Mars
    On Mars you weigh 42.2 lbs.
    
    Do you want to run again? (y/n) n
    

    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.

  12. Submit the source code file planet.cpp with the rest of the assignment as described in Deliverables.
References and More Information
  1. Astro-Matic 3000
  2. How Do We Weigh Planets?

Extra Credit

The following are worth extra credit points:

  1. Complete the assignment using pair programming with the same person. (2 points for all three projects)
  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 your own interesting function problem for the function worksheet. (1 point for completing correctly, 1 point for robust test cases, and 1 point for interest and creativity)
    1. Submit only the extra credit 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. Credit the source of the extra function, even if yourself, in the source code file. State the author and, if not original, the source using the tag "@source". For example:
      @author: Ed Parrish adapted from cplusplus example
      @source: http://www.cplusplus.com/forum/beginner/84104/
      

      If it is original work, then state how you came up with the idea after the @source tag.

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)
    • Compiles without warnings
    • 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. letterfreq.cpp
  5. weightfun.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: March 28 2020 @17:06:30