A8-Multi-Function Programs

Table of Contents


Objectives

  • Design a program using multiple functions as modules.
  • Develop functions as black boxes.
  • Use function declarations (prototypes).
  • Add block comments to function declarations.
  • Learn how rand() works.
  • Gain an understanding of the distribution of rand() numbers.

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 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 7.4.5: Arrays as Function Parameters.

Image

Project: Distribution of rand()

The random numbers we get from the rand() function are not truly random; instead the numbers are known as "pseudo-random." They are the result of a mathematical function that simulates randomness. This function would yield a pattern over time, but that time period is so long that for us, it's usually just as good as pure randomness!

In this project we look at the randomness of rand(), as used in the way we discussed in class. The distribution of rand() is supposed to be uniformally distributed over the range of numbers. The way to test the uniformity is to take a large number of random numbers, count how many of the random numbers are the same, and make a histogram (bar chart) of the counts. If all the counts are the same then the chart is flat and the randomness is uniform.

Project Specifications

Your solution for this project must only use techniques we have covered so far. You may want to start by using this worksheet: worksheet.txt

  1. Write a program that generates random numbers between 0 and 9 using rand()and analyzes the numbers generated by providing a chart and the following statistics:
    1. The count of each number generated
    2. the sum of the random numbers
    3. the average (arithmetic mean) of the random numbers
    4. the smallest (minimum) random number
    5. the largest (maximum) random number
    6. the range, which is the largest minus the smallest random number [1]
  2. You must name the source code file randfun.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. Create an integer array of 10 elements to store the count of each random value generated. Initialize each element to zero (0).
  4. Ask the user for the quantity of random numbers to generate and analyze, and no other input, as shown in the Example Runs.
  5. Generate the quantity of random numbers requested by the user and display a chart with the following information as shown in the Example Runs:
    1. the number being tallied
    2. the count of the each random number tallied
    3. a bar chart of the count
    4. the number of stars printed
  6. The bar chart must be scaled to a size of 50 stars for the largest count as shown in the Example Runs.
  7. 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 wording of the output. For the input shown you must get a similar, though random, output. The output must change properly if the inputs are different.
    This program analyzes the C++ rand() function
    
    Enter the number of random values: 1000
    
    Distribution of 1000 random numbers:
    
    ## Count Graph
    -- ----- -----
     0   105 *********************************************** 47
     1    98 ******************************************** 44
     2   104 ********************************************** 46
     3   106 *********************************************** 47
     4    99 ******************************************** 44
     5    88 *************************************** 39
     6    93 ****************************************** 42
     7    94 ****************************************** 42
     8   112 ************************************************** 50
     9   101 ********************************************* 45
    
    Summation: 4481
    Average value: 4.481
    Smallest value: 0
    Largest value: 9
    Range (arithmetic): 9
    
    Ideally, all bars would be the same length with very large numbers. Notice that the bars in the above are scaled to 50 stars maximum to prevent the bar from exceeding the width of the console window. The scaling amplifies the bar for small numbers as shown in the following run.
    This program analyzes the C++ rand() function
    
    Enter the number of random values: 1
    
    Distribution of 1 random numbers:
    
    ## Count Graph
    -- ----- -----
     0     0  0
     1     0  0
     2     1 ************************************************** 50
     3     0  0
     4     0  0
     5     0  0
     6     0  0
     7     0  0
     8     0  0
     9     0  0
    
    Summation: 2
    Average value: 2
    Smallest value: 2
    Largest value: 2
    Range (arithmetic): 0
    

    In the above example runs, 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. After displaying the output, exit the program.
  9. Your program must define between three and seven functions total, including main(), and call all the defined functions at least one time. As you organize your code into functions, remember that we write functions for these reasons:
    1. To organize our code into modules
    2. To reduce repeated code
    3. To allow for code reuse

    Make sure to include only the necessary details (abstraction) and to make appropriate use of parameters to generalize the functions. For information on array parameters see lesson 7.4.5: Arrays as Function Parameters.

  10. Structure your code to declare function prototypes before main() and function definitions after main() for all your functions except main().
  11. Remember to follow all the style rules from the last assignments, as well as the new rules we covered, including:
    1. Function comments (See: Function Comment Block) new!
    2. Avoid duplicating code (See: lesson 7.4.1)
    3. Indentation in functions and placement of curly braces (See: Indentation)
    4. No magic numbers (See: No Magic Numbers)
  12. Submit this project with the rest of the assignment as described in Deliverables.
Hints:
  • Tallying the random numbers is like the grade tallying we did in assignment 6: Score Tally.
  • Scale the numbers produced by rand() to match the index of the array. See lesson 7.2.5: Simulating Dice.
  • Remember to initialize variables, including the array elements, to achieve correct results.
  • To find minimum and maximum values see lesson 5.3.4: Maximum and Minimum Values.
  • To scale the bars in the chart, find the largest array element count. Divide 50 by the maximum count to get a length. Multiply this length value by each array element's count to compute the number of stars to print.
  • To display the variable count in the chart it is helpful to use the setw() formatting manipulator described on pages 49-51 (1/e: 53-55) of the textbook. For example to print a number within 5 spaces:
    cout << setw(5) << count;
    
References and More Information
  1. The Range (Statistics): calculation of the arithmetic range, which is often used in simple statistics.
  2. If you are still stuck try using this worksheet: worksheet.txt

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. According to comp.lang.c FAQ, the technique we discussed in class for getting random integers in a certain range is not optimal. Instead of
    rand() % SCALING_FACTOR + SHIFTING_VALUE
    
    they suggest
    rand() / (RAND_MAX / SCALING_FACTOR + 1) + SHIFTING_VALUE
    

    Add a second file named xc1_randfun.cpp with the above suggested technique. Then compare the results by running the two files multiple times and check for differences in the uniformity of the random numbers produced. In your README.txt, write a short explanation of the differences you saw and your conclusion on whether the second technique is an improvement. (1 point for the second file and 1 point for the explanation)

  3. Add ways to make the program code more interesting or exciting by going above and beyond the assignments specifications for extra credit. (0 for trivial or off topic extensions and up to 2 points for more interesting and exciting coding extensions)

    When extending the assignment, make sure you complete the requirements first and save the file with the specified name. Then create a second file with the file name extended_rand.cpp. Also, explain in the README.txt file what you did to make the code extension more interesting or exciting. If you implemented an idea from somewhere, remember to credit the source.

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

Program Compilation

  • 4: Source code compiles with no errors or warnings
  • 3: Source code compiles with 1 warning
  • 2: Source code compiles with 2 warnings
  • 1: Source code compiles with 3+ warnings
  • 0: Does not compile or wrong file turned in

Functionality

  • 10: Demonstrates mastery of the assignment
    • Applies concepts from the lessons appropriately
    • Meets all specifications (see above) with particularly elegant solutions
    • 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
  • 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
  • 0: Does not execute, not turned in or uses techniques not covered to date in the course

Program Style

  • 4: Code is well-documented including:
    • 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
    • Correct file name used
  • 3: Code has a minor documentation error
  • 2: Code has some documentation errors
  • 1: Code has many 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 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 8
  3. randfun.cpp
  4. extended_rand.cpp (optional 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: May 08 2017 @14:25:00