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 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 use only 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: Stellar Distances Redux

The stellar distances in miles program from assignment 4 is fairly lengthy. When programs get too long, we need to organize the code into smaller pieces called functions. Writing functions reduces the complexity of our programs by organizing the code into smaller, more manaeagable, pieces. With smaller pieces, we can more easily focus on each piece and write better code.

Project Specifications
  1. Update your stellar distances program from assignment 4 to use functions, correcting any errors you made in the prior program. If you are pair programming then you may combine the previous work of the two partners in a suitable way.
  2. You must name the source code file stellarfun.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. Minimum distance in miles
    2. Maximum distance in miles
    3. A 'y' or 'n' (without the quotes) for the repeat loop

    Ask for all user input 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 a function with the following signature exactly:
    /**
        Counts and lists the stars between a minimum and maximum distance.
    
        @param min The minimum distance in miles.
        @param max The maximum distance in miles.
        @return Number of stars found between and including min and max.
    */
    int listStars(double min, double max)
    

    When called, the function lists the stars within the range from min to max and returns the count of the stars within the specified range. Do NOT change the function's name, parameter types, number of parameters, or return type. Instead, pay attention to the intent of these items to guide your code development.

  6. Call the listStars() function from the main() function after collecting the user input. Print the count of the number of stars returned from the function in main() with the format shown in the Example Run. Include stars equal to the minimum and maximum distances in the listing.
  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.
    Enter a minimum and maximum distance from the Earth and I
    will list the stars within those distances.
    
    Enter the minimum distance in miles: 0
    Enter the maximum distance in miles: 7e13
    The stars between 0 and 7e+13 are:
    Sun
    Proxima Centauri
    Barnard's Star
    Wolf
    Sirius
    Epsilon Eridani
    Ross
    Procyon
    Tau Ceti
    9 star(s) found in this range.
    Run again? (y/n) y
    
    Enter the minimum distance in miles: 1e13
    Enter the maximum distance in miles: 5e13
    The stars between 1e+13 and 5e+13 are:
    Proxima Centauri
    Barnard's Star
    Wolf
    3 star(s) found in this range.
    Run again? (y/n) y
    
    Enter the minimum distance in miles: 3.5e13
    Enter the maximum distance in miles: 3.6e13
    The stars between 3.5e+13 and 3.6e+13 are:
    Barnard's Star
    1 star(s) found in this range.
    Run again? (y/n) n
    
    Thanks for checking on our stellar neighbors!
    

    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 words in italics, nor does the user input appear in italics. Notice the additional output of the number of stars that was not part of the previous assignment but is now required.

  8. Submit this project with the rest of the assignment as described in Deliverables.
Hints:
  • Increment a counter variable each time you print the name of a star.
  • Return the counter variable from the listStars() function.

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.

Project Specifications
  1. Write a program that prints the number of characters that match your personal name from a word or phrase entered by a user. If you are pair programming then each partner should 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.
    
        @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 while Jojo has two unique characters. 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 statement that allows the user to repeat the program until the user enters a single "x" (without the quotes).
  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): Ed Parrish
    The input contains 9 letters of your name.
    
    Enter a word or phrase (x to exit): The quick brown fox jumped over the lazy dog
    
    The input contains 13 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.1.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, remeber 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.
References and More Information
  1. Personal name: Wikipedia

Clickbait

Project 3: Random Clickbait Titles

Clickbait is Internet content of a sensational or provocative nature, whose main purpose is to attract attention and draw visitors to a particular web page. For this project, we will write a program to produce random clickbait titles on a topic selected by the user.

Project Specifications
  1. Write a program that produces ten (10) randomly selected clickbait titles from the list provided in the following starter code: randtitles.cpp. Do NOT change the name or types of the given variables. Note that the variable list can be accessed inside a function.
  2. The name of the source code file for this program must be randtitles.cpp and all your code must be in this file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. Write a function with the following signature exactly:
    /**
        Find the position of the first occurrence of word in sentence.
    
        @param sentence The string to search.
        @param word The string to find.
        @return The starting position of the first occurence of word in sentence,
                or -1 if not found.
    */
    int find(string sentence, string word)
    

    You must write your own function using loops and conditional statements and NOT simply call the string function find(). However, you may use the string functions length() and substr() as discussed in lesson 3.2.6. Do NOT change the function's name, parameter types, number of parameters, or return type. Instead, pay attention to the intent of these items to guide your code development.

  4. When running the program, ask the user for a single topic as input. Notice that the user must be able to enter spaces as part of the topic.
  5. After entering the topic, select 10 random titles from the list. Display the title with the user input substituted for the word [Topic]. Call the above find() function as needed to make the substitution.
  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 followed by a display of titles. Each time the program is run you must get a random list of outputs, and every title will display the topic words. The output must change every time the program is run.
    Enter a topic: C++ Programming
    
    Title ideas:
    1. 10 Ways To Learn About C++ Programming Easily and Effectively
    2. Here's What No One Tells You About C++ Programming
    3. 10 Ways To Learn About C++ Programming Easily and Effectively
    4. 7 Things Lady Gaga Has In Common With C++ Programming
    5. 13 Amazing Facts About C++ Programming
    6. 11 Ways Investing In C++ Programming Can Make You A Millionaire
    7. 10 Secrets That Experts Of C++ Programming Want You To Know
    8. The Modern Rules Of C++ Programming
    9. 5 Top Reasons Why You Face Obstacles In Learning C++ Programming
    10. 7 Shocking Truths About C++ Programming
    

    In the above instance of the program run, the user entered "C++ Programming" (without the quotes) as the topic. Notice that titles may randomly repeat as shown with 1 and 3 above.

  7. After printing the appropriate word, exit the program. Do NOT loop and run again.
  8. Submit this project with the rest of the assignment as described in Delieverables.
Hints:
  • To iterate through each character of the input string, see the for-loop in lesson 6.1.3: Iterating Strings.
  • Inside the loop, use an if-statement and substr() to test for the entire word "[Topic]".
  • In the find() function, declare all your variables before any loops or if-statements to avoid scope issues.
  • To select a random topic choose a random number for the array index. See lesson 7.2.5: Simulating Dice

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)
  3. In the stellarfun.cpp program, store the stellar distances in an array of double values and the star names in an array of string values. Then complete the stellarfun.cpp program with one if-statement and four or fewer relational expressions by using a loop and without using switch/case statements or other techniques we have not covered. (2 points)

    The program must work correctly to receive this extra credit.

  4. Write a second Random Clickbait Titles program so that the randomly selected titles do not repeat. Explain your technique in the README.txt file. Save the second file as clickbaitxc.cpp. (3 points)

    Hint: Use the Fisher-Yates Random Shuffle Algorithm or the Reservoir Sampling Algorithm. Make certain to acknowledge your source(s) with a URL or book and page number in both the README.TXT and a comment in your code to avoid plagarism. Adapt the algorithm and do not copy from a tutor or other person.

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 that matches the name of this assignment, 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. stellarfun.cpp
  4. charcount.cpp
  5. randtitles.cpp
  6. Optionally, clickbaitxc.cpp (extra credit)

Your assignment files 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, but must resubmit all your assignment files.

Last Updated: April 13 2017 @23:08:37