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. Make no changes to the main() function.

  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 as described by the function signature and comments. Remember, do not make any changes to the main() function.
  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.

    When you first start you will see warnings when compiling. Remember that code with warnings compiles but the warning is giving you hints about problems with the code.

  6. 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. There is no user input.
    *** Testing product0Sum ***
    product0Sum1(1, 2) should be 2: 2
    product0Sum2(3, 2) should be 6: 6
    product0Sum3(0, 3) should be 3: 3
    
    *** Testing sumToNumber ***
    sumToNumber1 should be 1: 1
    sumToNumber2 should be 6: 6
    sumToNumber3 should be 15: 15
    
    *** Testing makes12 ***
    makes12a(9, 12) should be true: true
    makes12b(9, 10) should be false: false
    makes12c(1, 11) should be true: true
    
    *** Testing or57 ***
    or57a(7) should be true: true
    or57b(10) should be true: true
    or57c(8) should be false: false
    
    *** Testing firstLast ***
    firstLast1("easy") should be 'e': e
    firstLast2("x") should be 'x': x
    firstLast3("zebra") should be 'a': a
    
    *** End of Tests ***
  7. 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.
Hints:

Image
Image source (modified)

Project 2: Computerized "Wisdom"

Random numbers are useful for a variety of purposes, such as encrypting data, simulating and modeling real world phenomena and for selecting random samples from data sets [1]. In this project we use random numbers to compose "wise" sayings by randomly selecting samples from lists of strings.

Project Specifications
  1. Write a program that randomly chooses a beginning and ending phrase from arrays of strings and joins them to create a sentence or saying.
  2. Name the source code file wisdom.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. The only input allowed is to ask the user if they want to compose another saying, as shown in the Example Run. The input is a single character.
  4. Write a single function, besides main(), with the following signature exactly:
    /**
        Compose a random saying.
    
        @return The randomly composed saying.
    */
    string composeSaying()
    
  5. Within the function, declare two string arrays, one for the start phrases and one for the end phrases. Use these phrases to compose a saying and do not add any other strings to these arrays.
  6. Also in the composeSaying() function, randomly select one string from the list of start phrases and one from the list of end phrases. Join the strings together, with a single space between them, and return the composed string. Do not output the saying in this function.
  7. From within the main() function, call the composeSaying() function and print the saying returned from the function call.
  8. Add a while statement in the main() function that allows the user to repeat the program by entering a "y" (without the quotes).
  9. Seed the random number generator in main() before the while loop.
  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 format of the output. The sayings must randomly change
    *** Random Wise Sayings ***
    
    Significant understanding ever stuns the onlooker.
    Do you want to compose another saying? (y/n) y
    
    Wondrous awe is often one floor above you.
    Do you want to compose another saying? (y/n) y
    
    Clear water is always a pleasure.
    Do you want to compose another saying? (y/n) y
    
    The flow of quizzes asked you a question?
    Do you want to compose another saying? (y/n) y
    
    Wondrous awe is good for you.
    Do you want to compose another saying? (y/n) n
    
    Goodbye.
    

    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 red italics, nor does the user input appear in aqua italics.

  11. Submit the source code file wisdom.cpp with the rest of the assignment as described in Deliverables.
Hints:
  • Limit the size of the random number to the size of the array using the modulus operator like the dice size is limited in Exercise 7.3 and lesson 7.3.5.
References and More Information
  1. Introduction to Randomness and Random Numbers: from random.org.

Image
Image source

Project 3: Enhancing Passwords

A simple technique for creating a password that is somewhat difficult to break is to pick a memorable phrase that is at least 4 words long, such as "I Love Cookies A Lot". Then, remove all whitespace from your phrase: "ILoveCookiesALot". Finally, replace all vowels with other characters from the keyboard following these rules:

  1. Replace every 'a' or 'A' character with a '@'
  2. Replace every 'e' or 'E' character with a '3'
  3. Replace every 'o' or 'O' character with a '0'
  4. Replace every 'i' or 'I' character with a '!'
  5. Replace every 'u' or 'U' character with a '^'

For this assignment, we are going to create a program that reads in phrases, converts the phrases to passwords using the above rules, and then outputs the passwords.

Project Specifications
  1. Write a program that generates passwords from user input.
  2. Name the source code file passwords.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 input string inside the main() function, and no other input, as shown in the Example Run. User input may contain spaces.

    For user input with spaces, review lesson 6.1.4.

  4. Write a function to create a password using the following starter code:
    /**
        Removes spaces and substitutes characters to create a password from str.
        @param str The input phrase, which may contain spaces.
        @return an enhanced password
    */
    string makePassword(string str) {
        string password = "";
        //for loop with if statements to remove spaces and replace characters
        return password;
    }
    

    Do not delete or change any code except comments. Notice and make use of the variable password.

  5. Inside the function write a for-loop that removes spaces and replaces (substitutes) letters using the following rules:
    1. Replace every 'a' or 'A' character with a '@'
    2. Replace every 'e' or 'E' character with a '3'
    3. Replace every 'o' or 'O' character with a '0'
    4. Replace every 'i' or 'I' character with a '!'
    5. Replace every 'u' or 'U' character with a '^'
  6. Call the makePassword() function from the main() function, passing as an argument the user input string from step 3. Display the returned value with double quotes (") around the enhanced password. Do not have any loop in main().
  7. Example Runs: The input prompts and outputs of the program must look exactly 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, including the label of "Enhanced password:" and the double quotation marks ("). However, the output must change properly if the inputs are different.
    Enter a passphrase: I Love Cookies A Lot
    Enhanced password: "!L0v3C00k!3s@L0t"
    
    Enter a passphrase: Warehousing in Aptos
    Enhanced password: "W@r3h0^s!ng!n@pt0s"
    

    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.

  8. Submit the source code file passwords.cpp with the rest of the assignment as described in Deliverables.
Hints:
  • If Mombot shows tilde ('~') characters in your output, she is telling you to remove spaces from the string instead of trying to assign a value to the character position in the string. The Windows 10 terminal window does not show some characters that remain behind such as null characters, which will give incorrect results that you cannot see without Mombot.
  • To remove characters from a string, append the acceptable characters to a new string and return the new string. See lesson 3.2.5 for information on contatenation.
References and More Information
  1. Password Checker Online
  2. Four Methods to Create a Secure Password You'll Actually Remember
  3. Choosing a Secure Password: advice from an expert.
  4. Password Strength: a classic!

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 results of the function call like the test cases do in the standard 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 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. wisdom.cpp
  5. passwords.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 09 2018 @02:30:45