A2-Math and Memory

Table of Contents


Objectives

  • Start practicing C++ commands
  • Start declaring and using numerical variables
  • Obtain and store user input
  • Perform arithmetic operations to solve problems using C++.
  • Make use of modulus operators
  • Work with mathematical functions.
  • Debug errors in your code
  • Write your first complete C++ programs!

Academic Honesty

Read the Scholastic Honesty Policy and Assignment Integrity policies of the syllabus. Here are some clarifications for this particular assignment:

  • You may not show your project work to another person or look at another person's project work until you complete and submit this assignment.
  • You may get help from others if you get stuck, but only if they do not show or tell you what to type.
  • Remember that the instructor performs similarity tests on programming project submissions, and copied or plagiarized code is very easy to detect.

This is a solo assignment.

Preparation

  1. Make sure you have completed the exercises from lesson 2.
  2. Complete the Review Exercises in CodeLab 2. These exercises will help prepare you for the problem-solving program and should be completed first.

Project Specifications

Note that these are solo programming projects and not pair-programming projects. Your solutions to these project must only use techniques we have covered so far.

Programming Style

For all programs, remember to follow all the style rules we covered including:

  1. File block comments.
  2. Placement of curly braces and indentation within curly braces.
  3. Limiting line length to about 80 characters.

    TextPad, and most other text editors, tell you both the line and column location, which lets you check the line length.

  4. Spaces before and after operators.

Image
Image source: Ed Parrish

Project 1: Math Worksheet

Use this worksheet to improve your understanding of how to convert math equations to C++ code. Refer to lesson 2 for more information on C++ maths.

For this worksheet, the user enters three numbers. You write code to display the value of the equations listed below using the three inputs.

Project Specifications
  1. Start by downloading the worksheet: mathwork.cpp.

    Add to the existing code to complete the project. Leave the existing code unchanged, except for comments.

  2. Name the source code file that you turn in mathwork.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. Add your name and the date to the file comment block at the top of the file where shown in the comments.
  4. User input is already coded into the worksheet.

    Do not add any other input commands or change the input order.

  5. C++ allows simple math like we use on a calculator. Convert each of the following equations to C++ code in the mathwork.cpp file using the `a`, `b`, and `c` user input already coded into the worksheet to complete the math expressions.
    1. Code the formula for the expenses of stock purchase using the following formula:

      exps = a + b - c

      where `a` is the share cost, `b` is the number of shares, and `c` is the cost of commissions.

      Code this equation into the mathwork.cpp program where indicated in the comments. See the Example Run below to verify correctness.

    2. Calculate the simple interest of a loan using the following formula:

      smpl = a * b * c

      where `a` is the principal, `b` is the interest rate, and `c` is the term.

      Code this equation into the mathwork.cpp program where indicated in the comments. See the Example Run below to verify correctness.

    3. Calculate the degrees celsius given using the following formula.

      cels = 5 / 9 (a - 32)

      Where `a` is the degrees in fahrenheit.

      Code this equation into the mathwork.cpp program where indicated in the comments. See the Example Run below to verify correctness.

    4. A fractional part of a decimal number is the part to the right of the decimal point. Use the floor() function to calculate the fractional part of the decimal number `a` using the following formula.

      fp = a - floor(a)

      Where `a` is from the user input already coded into the worksheet and ⌊ and ⌋ indicate the floor function in mathematics.

      Code this equation into the mathwork.cpp program where indicated in the comments. See the Example Run below to verify correctness.

    5. Calculate the periodic payment using the following formula:

      pymt = (a*b) / (1 - (1 + b)^-c)

      where `a` is the principal, `b` is the periodic interest rate, and `c` is the number of terms from the user input.

      Code this equation into the mathwork.cpp program where indicated in the comments for equation 5. See the Example Run below to verify correctness.

  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 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.
    ***Math Worksheet***
    Enter three numbers separated by spaces, and press the Enter key
    For example: 1.2 3.4 5.6[Enter]: 1.2 3.4 5.6
    Expression1 (-1): -1
    Expression2 (22.848): 22.848
    Expression3 (-17.1111): -17.1111
    Expression4 (0.2): 0.2
    Expression5 (4.08102): 4.08102
    
    ***Math Worksheet***
    Enter three numbers separated by spaces, and press the Enter key
    For example: 1.2 3.4 5.6[Enter]: 4.3 2 1
    Expression1 (-1): 5.3
    Expression2 (22.848): 8.6
    Expression3 (-17.1111): -15.3889
    Expression4 (0.2): 0.3
    Expression5 (4.08102): 12.9
    

    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. The values in (parentheses) are expected values when entering the example input of  1.2 3.4 5.6 .

  7. Display the output using the default formatting and precision for the numbers -- do NOT add any formatting statements to the code.
  8. After displaying the output, exit the program.
  9. Submit the source code file mathwork.cpp with the rest of the assignment as described in Deliverables.

Units of Length
Image source

Project 2: Fluid Measures

In the United States we use the system of measurement known as the United States customary units [1]. These units were developed from English units, as used in the British Empire, before the U.S. became an independent country.

Customary units are primarily used in commercial activities, as well as for personal and social use. Metric units are most often used in science and engineering, though Mechanical Engineering still often uses both customary and metric units [2].

In this project we explore the fluid volume measures by converting from ounces to gallons, quarts, pints, cups and remainder ounces. We do all our computations using whole numbers (int).

Project Specifications
  1. Write a program that asks the user for an input in ounces and displays the same measure as integer gallons, quarts, pints, cups, and ounces. The gallons, quarts, pints, cups, and ounces must collectively add up to the same measure. For example 42 ounces is:
    In whole numbers: 0 gallons, 1 quart, 0 pints, 1 cup, and 2 ounces.

    Hint: Develop an algorithm that uses division to find the number of gallons. Then use the remainder (%) operator to find out how many ounces remain. Repeat this process with the remaining ounces for the next highest volumes until only ounces remain. For an example, see the yards, feet and inches example in lesson 2.3.4.

  2. Name the source code file measures.cpp and include all your code in this single file along with a description of the algorithm.
    1. Make sure to spell the file name correctly, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.
    2. When starting your coding effort, restate the problem in the file comment at the top of the file after the word "Purpose:".
    3. Next, add a one-line comment (with numbers) for each step of the algorithm as we discussed in lesson 2.4.4. For example:

      // 1. Get the user input in ounces
      // ... add the other 5-6 steps after the first one, each on their own line
      

      Make sure to number the steps of the algorithm and clearly describe each step.

  3. Ask the user for the number of ounces (int), and no other input, as shown in the Example Run. In addition, display all numbers as whole numbers [3] with no decimal or fractional parts. Assume the user enters only whole numbers.
  4. Use both the division operator (/) and remainder operator (%) to calculate the various measures. At a minimum, include 4 division operations and 4 modulus operations in your code.
  5. 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.
    Enter number of ounces: 42
    In whole numbers: 0 gallons, 1 quarts, 0 pints, 1 cups, and 2 ounces.
    
    Enter number of ounces: 185
    In whole numbers: 1 gallons, 1 quarts, 1 pints, 1 cups, and 1 ounces.
    
    Enter number of ounces: 370
    In whole numbers: 2 gallons, 3 quarts, 1 pints, 0 cups, and 2 ounces.
    

    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.

  6. The plurality (words ending in "s") of the labels may not match the numbers, which is fine.

    We will learn how to correct this problem when we learn if-statements. However, do not use if-statements, or any conditional statements, in this program

  7. After displaying the output, exit the program.
  8. Submit the source code file measures.cpp with the rest of the assignment as described in Deliverables.
References and More Information
  1. United States customary units
  2. Imperial and US customary measurement systems
  3. Whole Numbers and Integers

 Profit
  i
Loss
  k

Project 3: Stock Profits and Loses

The stock of a corporation is all of the shares into which ownership of the corporation is divided. A single share of the stock represents fractional ownership of the corporation in proportion to the total number of shares. [1]

Stocks are often bought an sold on stock exchanges [2]. Stock brokers will buy and sell stocks for people for a fee. Many people buy shares of stocks as a speculative investment in a company they think will make money. When a company does well it's share price usually increases, allowing a sale at a higher price. Of course, a company may not do well and a shareholder then loses money when they sell. Thus there is always risk in a stock purchases.

In this project, we write a program to calculate profits and loses for stock purchases and sales. To calculate profits or losses, calculate the money remaining after selling the stock and subtract all the expenses including the purchase costs and both broker's fees. To calculate percentage (%) profit or loss, divide profit (or losses) by expenses and convert to a percentage.

Project Specifications
  1. Write a program that calculates the profit or loss of a stock share purchase and sale.

    Assume that stock shares are whole numbers with no fractional shares.

  2. Name the stocks code file stocks.cpp and include all your code in this single file.
    1. Make sure to spell the file name correctly, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.
    2. When starting your coding effort, restate the problem in the file comment at the top of the file after the word "Purpose:".
    3. Next, add a one-line comment for each step of the algorithm as we discussed in lesson 2.4.4. For example:

        // 1. Input and store data
        // ... add the other steps after the first one, each on their own line
        

      Make sure to number the steps of the algorithm starting at 1 and remember that all algorithms have at least three steps:

      1. Input and store data
      2. Process and store data
      3. Output information
  3. Ask the user for the following inputs (and no other input) in this order and each on their own line, as shown in the Example Run below:
    1. Shares purchased (integer)
    2. Price per share purchased
    3. Broker commission on purchase
    4. Price per share sold
    5. Broker commission on sale

    Assume the user enters only valid data.

  4. From the input data, calculate the profit or loss as both dollars and cents and as a percentage as shown in the Example Run below.

    Numbers may not display with exactly two decimal places, which is fine. Display the output using the default formatting and precision for the numbers - do NOT add any formatting statements to the code.

  5. 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 properly if the inputs are different.
    Welcome to the Stock Profit Calculator!
    Shares purchased: 100
    Price per share purchased: 20.25
    Broker commission on purchase: 25.25
    Price per share sold: 22
    Broker commission on sale: 25.25
    Profit (-loss): $124.5 or 5.99855%
    
    Welcome to the Stock Profit Calculator!
    Shares purchased: 123
    Price per share purchased: 12.34
    Broker commission on purchase: 30.33
    Price per share sold: 11.11
    Broker commission on sale: 32
    Profit (-loss): $-213.62 or -13.519%
    

    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.

  6. After displaying the output, exit the program.
  7. Submit the source code file stocks.cpp with the rest of the assignment as described in Deliverables.
References and More Information
  1. Stock: Wikipedia article.
  2. Stock exchange: Wikipedia article.
  3. Stocks: basics from the US Securities and Exchange Commission

People working together
Image source

Project 4: Pair Programming Worksheet

Pair programming is where two programmers work together at one computer to develop code projects. One, the driver, writes code while the other, the observer or navigator,[1] reviews each line of code as it is typed in. The two programmers switch roles frequently [1]. Students generally have higher confidence in their work and perform better when pair programming [2]. These effects were tested at Cabrillo College among other places [3].

Programming can be beneficial, but following certain guidelines is important to maximize success [4][5]. This project introduces you to the concepts and best practices of pair programming for our course programming projects.

Project Specifications
  1. Watch the video Introduction to Pair Programming, a professionally developed video (10 minutes).
  2. Save this Pair Programming Worksheet following the menu File > Download as > Plain Text (.txt), and save the file as pairprogramming.txt.
  3. Fill out and answer the questions in pairprogramming.txt without deleting any of the existing text.

    Provide thoughtful answers for full credit.

  4. Submit the pairprogramming.txt file with the rest of the assignment as described in Deliverables.
  5. For reference, here is a link to the The Rules of Pair Programming
References and More Information
  1. Pair programming: Wikipedia article
  2. The effects of pair-programming on performance in an introductory programming course.
  3. Pair Programming (Case Study 1)
  4. The Rules of Pair Programming
  5. All I Really Need to Know about Pair Programming I Learned in Kindergarten: Good suggestions on how to program in pairs.

Extra Credit

Completing the following is worth the extra credit points shown in parenthesis.

  1. Add an additional interesting and useful math expression derived from mathworks.cpp making use of at least two of the input variables and a math function. (1 point for completing with a math function and 1 point for interest, completeness and usefulness.)
    1. Submit the source code with the extra math expression in a file named xcmathwork.cpp.
    2. Describe what the expression is used for in your README.txt file.
    3. Include the data input section of the original mathwork.cpp file. Do NOT include the other mathworks problems. Only include your single new math problem.

      Note that if you do not use all the input variables in your expression then you must adjust the input section for the input variables actually used to prevent compiler warnings for unused variables.

    4. Follow the format of the previous expressions by assigning the solution to a unique output variable.
    5. Follow the output of the previous expressions by labeling the expression with a cout statement displaying the label Expression6 followed by the value assigned to the unique variable when entering the example values  1.2 3.4 5.6  and then the expression result itself, like:
      Expression6 (42): 42
      Expression6 (42): 210
  2. Describe in your README.txt which expressions in mathwork.cpp produce nan (not a number), when they produce nan, and explain why C++ should display nan. Label the explanation in your README.txt as "Explanation of nan". For example: (1 point)
    Explanation of nan: (explanation here).

    Hint: try entering 0 for the second number `b`.

  3. Declare and use constants integers in measures.cpp for all literal numbers in equations. (1 point)

    Look up magic numbers in the textbook (p.39) or on the internet to understand the solution to magic numbers.

  4. Attend an SI session for this assignment, sign the roll sheet and type in your README.txt, "attended SI" followed by the date(s) attended. (2 points)

Make sure to list the extra credit you complete in the README.txt file.

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 2 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)

  • 4: Demonstrates mastery of the program
    • Applies concepts from the lessons appropriately
    • Meets all specifications (see above)
    • Compiles without warnings
    • Runs to completion with no abnormal error conditions
    • Generates correct output given correct input
    • Correct file name
  • 3: 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
  • 2: Has some of the functionality expected of the program
    • Demonstrates some techniques from the lesson
    • Attempts to meet at least 1/2 of the specifications (see above)
    • Implementation seems excessively complicated.
    • May have 2-3 minor errors
  • 1: 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: Not turned in or uses techniques not covered

Pair Programming Worksheet

  • 4: Student completed and submitted the learning worksheet with masterful effort
  • 3: Student completed and submitted the learning worksheet with substantial effort
  • 2: Student completed and submitted the learning worksheet with minimal effort
  • 1: Student submitted the learning worksheet
  • 0: No learning worksheet submitted

Programming Style

  • 2: Code is well-documented including:
  • 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

Students submit some homework as they work on it like CodeLab. However, students must submit other homework in Canvas following the link to A2-Math and Memory. For detailed instructions see: How To Submit Homework Assignments. Include the following items when submitting to Canvas:

  1. README.txt file prepared by following the instructions for submitting homework.
  2. All the exercise files from Lesson 2
    • hellome.cpp
    • syntax.txt
    • variables.cpp
    • arithmetic.cpp
    • plan.txt
    • twice.cpp
    • errors.txt
    • erroneous.cpp
  3. mathwork.cpp
  4. measures.cpp
  5. stocks.cpp
  6. pairprogramming.txt
  7. Optionally, xcmathwork.cpp (extra credit)

Note: Make certain your programs compile before you turn them in. When a program does not compile then it does not function either. For all programming projects, you should expect little or no credit if your program does not compile and run. For more information see the Grading Criteria.

You must submit all the files needed to complete your assignment together. 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: March 01 2020 @18:56:10