A8-Multi-Function Programs

Table of Contents


Objectives

  • Use function declarations (prototypes).
  • Code void functions.
  • Design a program using multiple functions as modules.
  • Develop functions as black boxes.
  • Add block comments to function declarations.

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 work on the code together at the same computer.
  • You may not look at another student's code until you complete and submit this assignment, except for code you work on 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. Instead, ask them to show you other examples that you then apply to the project.
  • 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 8.
  2. Complete the Review Exercises in CodeLab 8. These exercises will help prepare you for the problem-solving programs and should be completed first.
  3. Read lesson 8.1.4: Arrays as Function Parameters.

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 comment blocks (See: Function Comment Block)
  3. Function naming conventions (See: Function Names)
  4. Indentation in functions and placement of curly braces (See: Indentation)
  5. No magic numbers. (Hint: make arrays of numbers const)
  6. Indentation in while statements and placement of curly braces
  7. 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).

  8. Meaningful variable names and consistent naming style (caps vs. underbars).
  9. Create the README.txt file following the instructions.

Image

Project 1: Function Worksheet Sequel

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: funwork2.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, replacing the words Your Name with your first and last name and Date Here with the current date.
  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 signature and comment block.

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

  5. Write the function definitions below main(), and their prototypes above main().
  6. 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.

  7. Compile and run the code when finished with each function to verify correctness. Check the test results and make any alterations to your function definitions as necessary. Do NOT change any code in main() beyond removing comments to call the functions and do not change the function headers.

    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.

  8. 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.
    ***Testing toLowerCase***
    toLowerCase1 must change A to (a): a
    toLowerCase2 must change Z to (z): z
    toLowerCase3 must change x to (x): x
    
    ***Testing isSentenceEnd***
    isSentenceEnd0 must return (false): false
    isSentenceEnd1 must return (true): true
    isSentenceEnd2 must return (true): true
    isSentenceEnd3 must return (true): true
    isSentenceEnd4 must return (false): false
    
    ***Testing scoresIncreasing***
    scoresIncreasing1 must return (true): true
    scoresIncreasing2 must return (false): false
    scoresIncreasing3 must return (true): true
    
    ***Testing printArray***
    printArray1 (1=1 3 4)
    real output: 1=1 3 4
    printArray2 (2=1 2 3 4)
    real output: 2=1 2 3 4
    printArray3 (3=0 1 2 3 4)
    real output: 3=0 1 2 3 4
    
    ***Testing doubleArray***
    doubleArray1 should return 2 6 8: da1=2 6 8
    doubleArray2 should return 2 4 6 8: da2=2 4 6 8
    doubleArray3 should return 0 2 4 6 8: da3=0 2 4 6 8
    
    *** End of Tests ***
    

    The actual output of calling printArray() appears on the line under the expected output. This placement allows easy verification of the correct output, including the correct spacing and equal sign. Also note that the output of evenAdd1() is produced in main() by calling printArray()--an example of function reuse!

  9. When all of the tests pass, upload your completed source code file with the rest of the assignment as described in Deliverables.
Hints:
  • Remember that a warning is not a failure to compile but must be corrected before submitting the project.
  • For an example of printing the elements of an array, see lesson 8.1.4: Arrays as Function Parameters.

Robot reading a document
Image source (modified)

Project 2: Reading, Rating and 'Rithmetic

Readability in writing is a measure of how easy a text is to understand for a given population. Populations are often characterized by their education level. For example, comic books are generally considered readable by fifth graders while college textbooks are readable by college students.

The most accurate way to measure readability is through a statistical survey of reader's understanding. However, such surveys are too expensive for the average writer. A less expensive and easier approach is to use a readability test. A readability test uses a formula to evaluate the readability of text. For instance, Microsoft Word and other popular word processors will measure the readability of a document by counting words, sentences and other properties and then using various formulae to predict their readability level.

In this project we measure the readability of various books using the Automated Readability Index, which was developed in the 1960's for the US military [1, 2]. We will count the number of characters, words and sentences in a text and calculate its readability score from this data. Here are some classic texts we will examine for readability:

Make certain you save these links as plain text (ASCII and NOT UTF-8). For Windows users, right-click the mouse button and select Save link as.... For Mac users control-click and select Save link as.... Optionally, you can download and unzip this file: books.zip. Download into the same folder as your program.

Project Specifications
  1. Use top-down design and functions to write a program that measures and reports the readability of a text file. Read the Hints below to guide your design process.
  2. Name the source code file readability.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. Use cin and input redirection to read the text file as follows:
    ./readability < input.txt
    

    Where input.txt is the text file to read.

  4. Count all the words entered. To keep the code simple, we define a word as any sequence of characters separated by whitespace, whether or not it is an actual word. Thus by our definition the following text contains 6 words:
    I do not like them, Sam-I-am.
    
  5. Count all sentences. For simplicity, we define a sentence as any group of words that ends with the punctuation:
    • exclamation mark (!)
    • period (.)
    • question mark (?)
    Any word group containing more than one punctuation mark counts as a single sentence. Thus by our definition the following text contains 5 sentences:
    You're A Mean One, Mr. Grinch by Dr. Suess.
    What?!!!! ...
    
    The five sentences are:
    You're A Mean One, Mr.
    Grinch by Dr.
    Suess.
    What?!!!!
    ...
    
  6. Count all the characters of every word. A word character does not include the following punctuation marks:
    • brackets ([) or (])
    • braces ({) or (})
    • colons (:)
    • commas (,)
    • double quotes (")
    • exclamation marks (!)
    • parentheses: (() or ())
    • periods (.)
    • question marks (?)
    • semicolons (;)
    All other ASCII characters from decimal 33 through 126 and 128 through 254 count as word characters including a dash (-) or an underscore (_). Thus the words in the following text all contain exactly 5 characters:
    I-say, "Stink?, [stank]; {stunk}: (ain't)"!
    
  7. Once you count the words, sentences and characters correctly, compute the average words per sentence and characters per word. Display the averages with this wording:
    Average words per sentence: value
    Average characters per word: value
    

    Where value is the calculated average. Print the averages with two decimal places.

  8. Next compute the Automated Readability Index (ARI) using the following formula:

    ARI = 4.71 * chars / words + .5 * words /sentences - 21.43

    Where "characters", "words" and "sentences" are the total number of words, characters and sentences. Display the ARI with this wording:

    Automated Readability Index: value
    

    Where value is the calculated ARI. Print the value with two decimal places.

  9. Use the Automated Readability Index (ARI) to determine a grade level from the following table provided by Wikipedia [3]:

    ARI   Grade Level
    1 Kindergarten
    2 First-Second Grade
    3 Third Grade
    4 Fourth Grade
    5 Fifth Grade
    6 Sixth Grade
    7 Seventh Grade
    8 Eighth Grade
    9 Ninth Grade
    10 Tenth Grade
    11 Eleventh Grade
    12 Twelfth grade
    13 College student
    14 Professor

    Display the Grade Level with the following words:

    Which is readable in: Grade Level
    

    Where Grade Level is the calculated Grade Level from the table. Display the labeling words, colon, and Grade Level all on one line as shown above.

  10. When designing the program, define between three and eight functions in addition to main(). Call all the functions at least once to perform an action.
  11. Define (implement) the functions after main() and their declarations (prototypes) before main().

    Remember to add block comments before each function declaration (prototype--the part before main()).

  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.
    ./readability < ham.txt
    67 words
    9 sentences
    208 characters
    
    Average words per sentence: 7.44
    Average characters per word: 3.10
    
    Automated Readability Index: -3.09
    Which is readable in: Kindergarten
    
    ./readability < london-call-215.txt
    34960 words
    1761 sentences
    156305 characters
    
    Average words per sentence: 19.85
    Average characters per word: 4.47
    
    Automated Readability Index: 9.55
    Which is readable in: Ninth Grade
    
    ./readability < dickens-2cities-98.txt
    138883 words
    6379 sentences
    621164 characters
    
    Average words per sentence: 21.77
    Average characters per word: 4.47
    
    Automated Readability Index: 10.52
    Which is readable in: Tenth Grade
    

    In the above example run, the user entered the values shown in aqua italics (for emphasis) in a terminal window 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 readability.cpp with the rest of the assignment as described in Deliverables.
Hints:

I suggest that you follow these suggestions to develop your code.

  • Review lesson 6.1.5: Processing Text Input and choose a way to process words. Put the loop to read the words in main().
  • Write code that tests whether or not a word has the punctuation that normally ends a sentence.
  • Write code that counts the number of characters in a word, excluding punctuation.
  • After your code can count words, characters and sentences correctly, then compute averages and the readability measurement.
  • Test your work using small text files in which you can manually count words, characters and sentences for comparison with your program output.
  • Once your program is working correctly, double check using the plain text files provided above and the output shown in the Example Runs.
References and More Information
  1. Automated Readability Index: PDF of Air Force document.
  2. How did the Automated Readability Index become an essential tool for technical writers?: some history from readable.com
  3. Automated Readability Index: Wikipedia article
  4. Project Gutenberg: free eBooks

Extra Credit and Extensions

The following are optional and worth extra credit points if the main program works well:

  1. Complete the programming project using pair programming. (2 points)
  2. Create your own interesting function problem for the function worksheet that modifies arrays or strings. (1 point for modifying arrays or strings, 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 xcfunwork2.cpp.
    2. Do not have any user input in the extra credit file.
    3. Extra function must have a string or array parameter to operate upon.
    4. 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 ***
      
    5. 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.
    6. Credit the source of the extra function, even if yourself, in the source code file. State the author and, if not original, the source using the tag "@source". For example:
      @author Ed Parrish adapted from cplusplus example
      @source http://www.cplusplus.com/forum/beginner/84104/
      

      If it is original work, then state how you came up with the idea after the @source tag.

  3. Complete the readability.cpp program with 7 or fewer relational expressions, including the test condition of any loops, and without using techniques we have not covered. (1 point)

    The program must work correctly to get this extra credit.

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 8 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

Function Worksheet

  • 5: All functions completed and program generates the correct output without error
  • 4: All functions completed but has a minor error
  • 3: Most functions completed or has some small errors
  • 2: At least half the functions completed or has some errors
  • 1: Few functions completed or has many errors
  • 0: Does not compile or wrong file turned in

Readability Project

  • 10: Demonstrates mastery of the assignment
    • Applies concepts from the lessons appropriately
    • Meets all specifications (see above) with particularly elegant solutions
    • Compiles without warnings
    • Runs to completion with no abnormal error conditions
    • Generates correct output given correct input
    • Behaves in a reasonable way in response to incorrect data
  • 8: Has all the functionality expected of the assignment
    • Demonstrates many techniques from the lesson
    • Attempts to meet all specifications (see above)
    • Implementation seems more complicated than necessary.
    • May have one minor error
  • 6: Has most of the functionality expected of the assignment
    • Demonstrates some techniques from the lesson
    • Attempts to meet all but one of the specifications (see above)
    • Implementation seems excessively complicated.
    • May have 2-3 minor errors
  • 4: Has some of the functionality expected of the assignment
    • Demonstrates some techniques from the lesson
    • Attempts to meet at least 1/2 of the specifications (see above)
    • Implementation seems excessively complicated.
    • May have more than 3 minor errors
    • AI not correctly trained
  • 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: Does not execute, not turned in or uses techniques not covered in course

Program Style

  • 3: Code is well-documented including:
    • Correct file name used
    • Name, date, and program description in file comment block
    • Follows specified format for file comment block
    • Has a function comment block for all function declarations following the specified format
    • Proper use of spaces around operators
    • No tab characters are present in the source code
    • As described in How To Document and Organize C++ Code
  • 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 Exercises

Number 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 A8-Multi-Function Programs, following the instructions for submitting homework. Include the following items for grading:

  1. README.txt file
  2. All the exercise files from Lesson 8
  3. funwork2.cpp
  4. readability.cpp

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 02 2020 @21:33:07