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.

  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 capitalize ***
    capitalize('a') must be ('A'): 'A'
    capitalize('B') must be ('B'): 'B'
    capitalize('z') must be ('Z'): 'Z'
    capitalize('9') must be ('9'): '9'
    
    *** Testing isLetter ***
    isLetter('d') must be (true): true
    isLetter('A') must be (true): true
    isLetter('Z') must be (true): true
    isLetter('9') must be (false): false
    isLetter('!') must be (false): false
    
    *** Testing sleepIn ***
    sleepIn(false, false) must be (true): true
    sleepIn(true, false) must be (false): false
    sleepIn(false, true) must be (true): true
    sleepIn(true, true) must be (true): true
    
    *** Testing toUpper ***
    toUpper("abc") must be ("ABC"): "ABC"
    toUpper("A3bc2d") must be ("A3BC2D"): "A3BC2D"
    toUpper("abCdeZ") must be ("ABCDEZ"): "ABCDEZ"
    toUpper("") must be (""): ""
    
    *** Testing findName ***
    findName("Alfa") must be (0): 0
    findName("Kilo") must be (10): 10
    findName("Zulu") must be (25): 25
    findName("Ajax") must be (-1): -1
    findName("zulu") must be (-1): -1
    
    *** 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.

Functional
Input
Validation

Project 2: Getting Reals

In lesson 5.3.5 we saw that we can use loops and if statements to validate user input. For example, we may ask for a positive number and instead the user may enter a negative number:

Enter a positive number: -42
You must enter a positive number!
Enter a positive number:

In the above our program caught the incorrect number entered. As we saw in lesson 5.3.7, we can go further and catch more errors where the user enters an incompatible type of data, such as entering a string for a number, by testing cin for failure. For example:

Enter a positive number: one
You must enter digits, not words
Enter a positive number:

We may need to get user input in several locations. To avoid duplicate code and coding errors, we organize the code into functions. We may then simply call the function whenever we need to get valid user input.

Project Specifications
  1. Write a program that asks the user for a number and then calls a function to get the user input.
  2. Name the source code file realfun.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 for a single numerical input, and no other input, as shown in the Example Run.
  4. Write one and only one function, besides main(), with the following header:
    /**
        Displays a specified prompt message and then reads a double.
        @param prompt a string with the prompt text.
        @return a double which is read from the keyboard.
    */
    double getReal(string prompt)
    
    1. The name of your function must be either get_real() or getReal() 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 prints the prompt string followed by a space and reads a type double floating-point number from cin. See lesson 5.3.5: Input Validation for an example.
    3. After reading the number, the check cin for failure. If cin fails, print an error message (starting with the word "Error") and allow the user to re-input the number. See lesson 5.3.7: Handling cin Failure for an example.
    4. When the user enters a correct number, the functions returns the validated number.
  5. Call the function from main() and print the number returned from the getReal() function.
  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 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.
    Enter a floating-point number: one
    Error: enter digits only, not letters.
    Enter a floating-point number: 123.45
    You entered: 123.45
    (End of program)
    

    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. The values in (parentheses) are expected values when entering the example input.

  7. Your program must use a bool variable to control the validation loop. See lesson 5.3.8: Using Boolean Variables for more information.
  8. Submit the realfun code file realfun.cpp with the rest of the assignment as described in Deliverables.
References and More Information
  1. lesson 5.3.5: Input Validation
  2. lesson 5.3.7: Handling cin Failure
  3. lesson 5.3.8: Using Boolean Variables

Image
Image source

Project 3: Juice Orders Redux

In the juice project from assignment 4, we saw that encoding and decoding information can save memory space and speed transmission of data. However, the code for the assignment is fairly lengthy.

In this project, we redo our juice order decoder 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 juice order decoder 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 juicearray.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, as shown in the Example Run below:
    1. A single order code like: WG12 (no spaces allowed!!)
    2. A 'y' or 'n' (without the quotes) for the repeat loop

    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:
    /**
        Returns the full juice name for a given code.
    
        @param type The juice code to translate
        @return The full name of a juice code or empty string ("") for no match.
    */
    string decode(string type)
    

    Call the function from main(). When called, the function returns the full name of a juice code or an empty string ("") for no match. Do not code any cin or cout statements in this function. As before, the program must decode the following juice types:

    Code Juice Type
    ABCApple-Beet-Carrot
    AKApple-Kale
    CLCelery-Lemon
    CSLCucumber-Spinach-Lemon
    KPLKale-Parsley-Lemon
    OCOrange-Carrot
    SACSpinach-Apple-Carrot
    WGWheat Grass
    WLMWatermelon-Lime-Mint

    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. Start by moving your decoding if statements into the decode() function. Your program should still operate the same after this step.
  7. Next, revise the decode() function to store the codes in an array of strings and the spelled out juice names in another array of strings such that the indexes of the codes and names are the same. For example:
    const string CODES[] = { "ABC", "AK",, ... };
    const string NAMES[] = { "Apple-Beet-Carrot", "Apple-Kale", ... };
    

    Remember to declare your arrays constant as shown above.

  8. 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.
  9. Keep the number of your relational operators to less than or equal to eight (8) in the entire program and do not use any techniques we have not covered so far.
  10. 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 (?). For the input shown you must get the same output. However, the output must change correctly if the inputs are different.
    Welcome to Pulper Prize Juice Company!
    
    Enter the juice order code: CSL12
    12 bottles of Cucumber-Spinach-Lemon
    
    Another item (y/n)? y
    
    Enter the juice order code: AK7
    7 bottles of Apple-Kale
    
    Another item (y/n)? y
    
    Enter the juice order code: XY123
    We don't make that juice.
    
    Another item? (y/n) n
    
    Your juice order will be right up!
    

    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.

  11. Submit the source code file juice.cpp with the rest of the assignment as described in Deliverables.

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. Allow the user to enter uppercase or lowercase code letters in juicearray.cpp without using techniques we have not covered and while still meeting all the specifications. (1 point)
  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 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. 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.

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. realfun.cpp
  5. juicearray.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: October 20 2019 @16:29:15