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 comment block.

    Do NOT change any of the function signatures and do NOT make any changes to the main() function besides uncommenting code.

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

    You may add cout to debug code but please remove it 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.

    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.

  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.
    *** Testing alternate ***
    Variable turn is set to a 1.
    alternate1 must change turn to (2): 2
    alternate2 must change turn to (1): 1
    alternate3 must change turn to (2): 2
    
    *** Testing is123 ***
    is123(0) must be (false): false
    is123(1) must be (true): true
    is123(2) must be (true): true
    is123(3) must be (true): true
    is123(4) must be (false): false
    
    *** Testing rand1toN ***
    rand1toN1 must return numbers from (1 to 1): 1 1 1 1 1 1 1 1 1 1
    rand1toN3 must return numbers from (1 to 3): 3 2 1 3 2 2 1 2 3 3
    rand1toN5 must return numbers from (1 to 5): 2 2 5 1 5 3 4 5 2 1
    
    *** Testing countLetterB ***
    countLetterB1 must be (1): 1
    countLetterB2 must be (2): 2
    countLetterB3 must be (3): 3
    countLetterB4 must be (4): 4
    
    ***Testing equalSecondLast***
    equalSecondLast1 must return (false): false
    equalSecondLast2 must return (true): true
    equalSecondLast3 must return (false): false
    equalSecondLast4 must return (true): true
    
  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.

Sticks lying on surface
Image credit

Project 2: Coding a Game AI

In this project, we continue development of our game of sticks from assignment 6, Project 2 by adding an option to play against the computer.

Artificial intelligence (AI) is a branch of computer science that simulates intelligent behavior in computers. An AI must perceives its environment and takes actions that maximize its chance of successfully achieving its goals [1]. For this project, we will simulate an opponent using a simple technique: random numbers. The environment is the game of sticks and the goal of the AI is to make a valid move in the game, a move that may change every turn.

The overall game structure is similar to the last project, but we need to add an option for playing against the computer, which will require some adjustment of the logic inside the main game loop.

Play options:
1. Play against a human
2. Play against the computer
Choice (1-2): 2

The computer always plays as the second player and we will generate the AI moves inside a function. The function will return a random number between one (1) and three (3), with a check that the random number does not exceed the number of sticks remaining. To generate a random number for the number of sticks in a move (1-3), call the rand() function and use the modulus operator to limit the size of the number. For an example, see how to limit the size of a number, see Exercise 7.3 and lesson 7.3.5.

When the AI makes a move, store the move in an array for later analysis. The index of the array element is the move number and the value of the element is the number of sticks the AI takes. Since array indices start at zero (0), we may either adjust each index by subtracting one from the number of sticks to get the array index, or simply not use element zero of the array.

Project Specifications
  1. Update the Game of Sticks project from assignment 6, Project 2 to add an AI such that the program meets all the original specifications except for the changes noted below.

    If you had problems completing the previous assignment, see the instructor's solution in Canvas or attend SI.

  2. Name the source code file sticks7.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. After asking for the number of sticks, ask the user if they want to play against a human or the computer. Allow the user to make selections by entering a number for the following actions as shown in the Example Runs:
    1. Play against a human
    2. Play against the computer
  4. Continue the game by alternating between the two players, allowing each to pick up between 1 and 3 sticks as shown in the Example Runs.

    If the user chooses option 2, the second player is the AI; otherwise, if the user chooses option 1 the other player is a human as in the last assignment. Remember that the last player to pick up a stick loses.

  5. Before each play of the human, show the number of sticks remaining as shown in the Example Runs. For the AI move, do NOT show the number of sticks remaining.
  6. To implement the random AI moves, write a single function, besides main(), with the following signature exactly:
    /**
        Generates a random AI move.
    
        @param sticks The number of sticks remaining.
        @return a valid random move between 1 and 3.
    */
    int moveAI(int sticks)
    

    Other functions may be added to the game but no more than three besides main().

  7. Within the moveAI() function, call rand() to calculate the number of sticks selected. Check if the number of sticks selected is less than or equal to the number of sticks remaining and return a valid number.

    Use an if-statement to to verify the random move does not exceed the number of sticks remaining. Do not add additional intelligence to the AI for this assignment.

  8. From within the main() function, call the moveAI() function and get the number of sticks selected by the AI and save this number in an array to analyze the AI moves at the end of the game.

    Display the AI move using the message wording shown in the Example Runs. For example:

    AI takes 2
    
  9. At the end of each game, display the moves made by the AI using a for-loop to display the values in the format of sticks-remaining:sticks-taken. For example:
    For the number of sticks remaining the AI takes:
    9:2
    4:3
    

    The number before the colon (:) is the number of sticks before the move was applied. The number after the colon is how many sticks were chosen by the computer.

    Hint: Use the for-loop to go through the sequence of array elements. If an element is not equal to 0, then display it; otherwise, do not display the element.

  10. As in the prior game version, include a do or while loop that allows the user to repeat the game with the same number of sticks by entering a "1" (without the quotes) at the end of each game as shown in the Example Runs.
  11. Seed the random number generator in main() before any loop or function call.
  12. 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.
    Welcome to the game of sticks!
    How many sticks to start with (10-100)? 12
    Play options:
    1. Play against a human
    2. Play against the computer
    Choice (1-2): 2
    
    There are 12 sticks on the board.
    Player 1:How many sticks to take (1-3)? 3
    AI takes 2
    
    There are 7 sticks on the board.
    Player 1:How many sticks to take (1-3)? 3
    AI takes 3
    
    There are 1 sticks on the board.
    Player 1:How many sticks to take (1-3)? 1
    
    You lose
    For the number of sticks remaining the AI takes:
    9:2
    4:3
    
    Play again (1 = yes, 0 = no)? 1
    
    There are 12 sticks on the board.
    Player 1:How many sticks to take (1-3)? 3
    AI takes 3
    
    There are 6 sticks on the board.
    Player 1:How many sticks to take (1-3)? 3
    AI takes 3
    
    AI loses
    For the number of sticks remaining the AI takes:
    9:3
    3:3
    
    Play again (1 = yes, 0 = no)? 0
    
    Welcome to the game of sticks!
    How many sticks to start with (10-100)? 10
    Play options:
    1. Play against a human
    2. Play against the computer
    Choice (1-2): 1
    
    There are 10 sticks on the board.
    Player 1:How many sticks to take (1-3)? 3
    
    There are 7 sticks on the board.
    Player 2:How many sticks to take (1-3)? 3
    
    There are 4 sticks on the board.
    Player 1:How many sticks to take (1-3)? 3
    
    There are 1 sticks on the board.
    Player 2:How many sticks to take (1-3)? 1
    
    Player 2 loses.
    Play again (1 = yes, 0 = no)? 0
    

    In the above example runs, the users 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.

  13. Submit the source code file sticks7.cpp with the rest of the assignment as described in Deliverables.
Hints:
  • Limit the size of the random number to the number of sticks allowed (1-3) using the modulus operator. For an example, see how the dice size is limited in Exercise 7.3 and lesson 7.3.5.
References and More Information
  1. Artificial intelligence: Wikipedia
  2. Introduction to Randomness and Random Numbers: from random.org.

Image
Image source

Project 3: Texting to English Converter Redux

In this project, we redo our texting to English converter from assignment 4, Project 2 to minimize if-statements and relational operators by using arrays and loops. In addition, we package the translator into a function.

Project Specifications
  1. Redo your texting to English converter from assignment 4 to use functions, both correcting any prior errors made and extending the program as described below.

    If you are pair programming then you may start with the previous combinded work of the two partners.

  2. Name the source code file sms7.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 message to translate, and no other input, as shown in the Example Run.

    While the user will enter a phrase, translate the input one word at a time with a loop. See lesson 6.1.5: Processing Text Input for how to process text word-by-word in a loop. Use a single while-loop like the following in main():

    while (cin >> word)
    {
        // Call translate function
    }
    
  4. Allow the user to exit the program by pressing Ctrl+Z on Windows and Ctrl+D on Mac or Linux.
  5. The program must translate the following SMS text abbreviations to English at a minimum:
    Abbr. Translation
    4for
    cusee you
    l8late
    l8rlater
    m8mate
    rare
    uyou
    uryou are
    wuwhat's up?

    Notice that "l8" is the letter "el" followed by an eight, NOT eighteen. The same is true for "l8r".

    You may translate more abbreviations as long as the extra words do not interfere with the above translations. Do not change untranslated words.

  6. Store the abbreviations in an array of strings and the translation in another array of strings. For example:
    const string ABBR[] = {"4", "cu", ... };
    const string XLAT[] = {"for", "see you", ... };
    

    Remember to declare your arrays constant as shown above.

  7. Keep the number of your relational operators to less than or equal to five (5) by using a for-loop to translate the abbreviations and without using any techniques we have not covered so far.

    Hint: see lesson 7.2.4: Finding Elements in an Array

  8. Define a function to perform the translation and call the function from the main() function. The function must have both a string parameter and return a string value.
  9. 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 correctly if the inputs are different.
    *** SMS Decoder ***
    Enter an SMS message and press Enter (Ctrl+Z/Ctrl+D to exit)
    Hey m8 wu
    Hey mate what's up? <Enter>
    Where r u ? u r l8 4 class
    Where are you ? you are late for class <Enter>
    cu l8r
    see you later <Ctrl+Z>
    

    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. To get the values to appear on new lines, the user preceded the input by pressing the Enter ↵ or Return keys as indicated with <Enter>.

  10. Submit the source code file sms7.cpp with the rest of the assignment as described in Deliverables.
Hints:
References and More Information
  1. Abbreviation: Wikipedia
  2. SMS language: Wikipedia
  3. Text Messaging Abbreviations & Shortcuts
  4. Huge List of Texting and Online Chat Abbreviations

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 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.
  4. Translate both upper and lower case variants of SMS abbreviations in sms7.cpp without changing the case of non-abbreviated words, without changing the arrays, and without using C++ statements we have not studied so far (2 points). For example:
    *** SMS Decoder ***
    Enter an SMS message and press Enter (Ctrl+Z/Ctrl+D to exit)
    Bye M8 cU L8r
    Bye mate see you later
    

    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. sticks7.cpp
  5. sms7.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 28 2018 @16:49:28