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
  • 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 for comments as instructed.

  2. Add your name and the date to the file comment block at the top of the file where shown in the comments.
  3. No user input is required for this project and do not add any.
  4. Write the required functions as described by the function signature and comments.
  5. 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.

  6. When all of the tests pass, upload your completed source code file with the rest of the assignment as described in Deliverables.

Image

Project 2: Counting Characters

A personal name, or full name, refers to the set of names by which an individual is known and that can be recited as a word-group, with the understanding that, taken together, they all relate to that one individual [1].

For this project, you will ask the user to enter a word or phrase and then count the numbers of letters in the input that match the unique letters of your name, excluding spaces. If you have two or more letters in you name that are the same, only test for one of the letters. For example, if your name is "Ed Parrish" and the user enters "Egg Roll" the program will report a count of two (2) letters.

When pair programming, you may still work together with your partner to complete this program. However, each student will turn in a program that only counts the characters of their name. Thus the programs will vary in the part that detects the letters of their name.

Project Specifications
  1. Write a program that prints the number of characters that match your personal name (full name that matches grade feedback in Canvas) from a word or phrase entered by a user. If you are pair-programming then each partner must turn in files that match their name only.
  2. You must name the source code file charcount.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, and no other input, as shown in the Example Run. Ask for all user input in the main() function and exit the program when the user enters a single letter "x" (without the quotes).
  4. Write a function with the following signature exactly:
    /**
        Counts the number of letters in str that match the unique letters
        (not spaces) of my name. However, the input string may have duplicate
        letters that are counted.
    
        @param str a string with a word or phrase
        @return the number of letters.
    */
    int countLetters(string str)
    

    When called, the function counts the number of letters in str that match unique characters in your name, both upper and lower case, and returns that count. For example, John has four unique characters in his name while Jojo has two unique characters. Thus entering "JJ" would return 2 characters for John and 2 for Jojo. 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. Do not use tolower(), toupper() or other techniques we have not covered.

  5. After calling the function, display the returned count of characters in the main() function.
  6. Add a while or do-while statement in main() that allows the user to repeat the program until the user enters a single "x" (without the quotes).

    Do NOT forget to include a getline() statement inside the loop.

  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. Your program must count the characters for the set of names by which you are known to the instructor (like in feedback on previous assignments) and include your first and last names at a minimum.
    Enter a word or phrase (x to exit): Egg Roll
    The input contains 2 letters of your name.
    
    Enter a word or phrase (x to exit): eeee
    The input contains 4 letters of your name.
    
    Enter a word or phrase (x to exit): Ed Parrish
    The input contains 9 letters of your name.
    
    Enter a word or phrase (x to exit): The quick brown fox jumps over the lazy dog
    
    The input contains 12 letters of your name.
    
    Enter a word or phrase (x to exit): 12345
    The input contains 0 letters of your name.
    
    Enter a word or phrase (x to exit): x
    
    You have a name we can count on!
    

    In the above example run, the programmer's name is "Ed Parrish". Notice that the count is based on what the user entered and ignores duplicate characters in the programmer's name. The user entered the phrase shown in italics (for emphasis) to produce the output. Your program does NOT print the characters in italics, nor does the user input appear in italics.

  8. Submit this project with the rest of the assignment as described in Deliverables.
Hints:
  • Iterate through each character of the input string with a for-loop like we discussed in lesson 6.2.3: Iterating Strings.
  • Inside the loop, use if-statements to test for each character of your name.
  • To convert a character between upper and lower case, remember how the ASCII table is organized. The character 'A' is 65 and 'a' is 97. The difference between the two is 32. As an example, if a character is less than 'a' you can convert it to lower case by adding 32 (optional).
References and More Information
  1. Personal name: Wikipedia

Image
Source: designed by Freepik

Project 3: Buying the Most Toys

We know a young child who likes toys. We want to buy the child the most toys we can to make the biggest impression! However, we only have a certain amount of money we can spend. We are looking at a list of toy prices and we want to maximize the number of toys that we can buy without going over your budget.

To help us make the decision, we write a C++ program that tells us how many toys we can buy on the list with the amount of money we can spend.

Project Specifications
  1. Write a program that tells us the most individual toys we can buy from a list of prices, without duplicating any toy and without going over budget.
  2. Name the source code file toys.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 the amount of money to spend, and no other input, as shown in the Example Run.
  4. Define a constant array with the following prices in your program.
    1.99, 2.49, 3.98, 4.99, 5.49, 6.98, 7.99, 10.75
    

    Make sure to add the prices to the array in the same order as given above.

  5. Define a function to count the number of toys we can buy for a given amount of money. Call the toy-counting function from the main() function.
  6. Add a while or do-while loop to main() that asks for the amount of money to spend indefinitely until the users enters an amount of money less than or equal to zero.
  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.
    ** Toy Maximizer! **
    
    Enter the amount of money to spend: 20
    Number of toys: 5
    Money remaining: 1.06
    
    Enter the amount of money to spend: 30
    Number of toys: 6
    Money remaining: 4.08
    
    Enter the amount of money to spend: 0
    You're the best!
    

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

  8. Submit the source code file toys.cpp with the rest of the assignment as described in Deliverables.
Hints:
  • Print the number of toys inside the toy-counting function (spec 5). We may use cout in any function.
  • To avoid magic numbers with the array of prices, put const in front of the array.

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 the problem solving programs. (1 point)

    Must have functions besides main() for this extra credit.

  3. 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 aspects like the test cases in the standard project.
    5. Be sure to credit the source of the extra function if not original in the source code file and README.txt.

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 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. charcount.cpp
  5. toys.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: November 06 2017 @01:03:57