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. Convert each of the following equations to C++ code in the worksheet.
    1. C++ allows simple math like we use on a calculator. For expression 1, code the following formula into the program.

      x = a + b - c

      Where `a`, `b`, and `c` are the user input already coded into the worksheet.

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

    2. Calculate the gallons of fuel needed to travel `b` miles where `c` is the MPG (miles per gallon) of the vehicle. For expression 2, calculate the gallons of fuel needed using the following formula.

      fuel = b / c

      Where `b` and `c` are the user input already coded into the worksheet.

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

    3. An arithmetic mean is the average obtained by dividing the sum of the numbers by their number. The "sum" means to add up a sequence of numbers. For expression 3, calculate the mean of the input using the following formula.

      mean = (a + b + c) / 3

      Where `a`, `b` and `c` are the numbers to sum from the user input already coded into the worksheet and 3 is the number of values.

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

    4. An integer part of a decimal number is the part to the left of the decimal point. For expression 4, use the floor() function calculate the integer part of the decimal number a using the following formula.

      aInt = \lfloor a 
floor

      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. The sum of the first `n` terms of a geometric series is given by the following formula for b ≠ 1:

      geo = a * ((1 - b^c) / (1 - b))

      where `a` is the first term, `b` is the common ratio and `c` is the number of terms (`n`) 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[Enter]: 1.2 3 4
    Expression1 (0.2): 0.2
    Expression2 (0.75): 0.75
    Expression3 (2.73333): 2.73333
    Expression4 (1): 1
    Expression5 (48): 48
    
    ***Math Worksheet***
    Enter three numbers separated by spaces, and press the Enter key
    For example: 1.2 3 4[Enter]: 4.3 2 1
    Expression1 (0.2): 5.3
    Expression2 (0.75): 2
    Expression3 (2.73333): 2.43333
    Expression4 (1): 4
    Expression5 (48): 4.3
    

    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 .

  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.

Division and modulus operators
Image source: Ed Parrish

Project 2: Verifying Identification Numbers

The Luhn algorithm is a checksum formula used to validate identification numbers like credit card numbers, mobile phone identifiers, Medicare provider numbers, and survey codes for MacDonalds and Taco Bell. A checksum is a number calculated from digital data to catch errors in entry, storage or transmission. The Luhn algorithm, created by IBM scientist Hans Peter Luhn in the 1950s, is designed to protect against accidental errors such as mistyping a number. For example, it will detect if two numbers are transposed (reversed order). [1]

The Luhn algorithm works by adding a check digit to the end of an identification number. Thus a number like 1234 will have an extra digit added, like: 12344. To calculate the check digit, the Luhn algorithm sums the digits of the number in a special way to generate a single check digit. For example, the number 1234 is summed as 1 + 2 + 3 + 4 = 10. However, the Luhn algorithm adds additional steps as described below.

Verifying an Id Number with the Luhn Algorithm

For this project, we will verify identification numbers using the Luhn algorithm for numbers up to eight digits. For our example, assume an eight-digit identification number of 27998715 where 5 is the check digit. The algorithm steps are:

  1. Separate each digit of the starting number as shown in row 1 of the example below. The 5 is digit 1 and will be the check digit.
    2   7   9   9   8   7   1   5
    
  2. The next step is to double all the even-numbered digits starting from the right, keeping the odd-numbered digits the same.
    4   7   18  9   16  7   2   5
    
  3. Sum the digits of all the even-numbered digits as shown.
    4   7 1+8=9 9  1+6=7 7  2   5
    
  4. Next sum all the digits, which is 50 for the example number.
    4   7   9   9   7   7   2   5 = 50
    
  5. Verify the id number is valid by comparing the last digit of the sum is zero (evenly divisible by 10).
Project Specifications
  1. Write a program that verifies identification numbers using the Luhn algorithm described above.
  2. Name the source code file luhn.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. Separate each digit of the id number.
        // ... add the other 4 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 to input a single integer number, and no other input, as shown in the Example Run.
  4. Use both the division operator (/) and remainder operator (%) to separate digits from the integer number input by the user. Store each digit in a separate integer variable.

    At a minimum, your code must include 7 division operations and 7 modulus operations minimum to extract the digits from the number input by the user. See lesson 2.3.4 for example code.

  5. Sum the digits following the Luhn algorithm described above and generate the check digit. Display the Luhn sum and checksum as shown in the Example Runs.
  6. Example Runs: The 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 input is different.
    Welcome to the Id Number Validator!
    Please enter the id number (8-digits maximum): 12344
    Luhn sum: 20
    Checksum: 0
    If the checksum is 0 then the number is valid.
    
    Welcome to the Id Number Validator!
    Please enter the id number (8-digits maximum): 12345
    Luhn sum: 21
    Checksum: 1
    If the checksum is 0 then the number is valid.
    
    Welcome to the Id Number Validator!
    Please enter the id number (8-digits maximum): 87650
    Luhn sum: 20
    Check digit: 0
    If the checksum is 0 then the number is valid.
    
    Welcome to the Id Number Validator!
    Please enter the id number (8-digits maximum): 87654
    Luhn sum: 24
    Checksum: 4
    If the checksum is 0 then the number is valid.
    
    Welcome to the Id Number Validator!
    Please enter the id number (8-digits maximum): 27998715
    Luhn sum: 50
    Checksum: 0
    If the checksum is 0 then the number is valid
    

    In the above example runs, the user entered the value 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.

  7. After displaying the output, exit the program.
  8. Do not use if-statements, strings, loops, or other techniques we have not covered yet.
  9. Submit this project with the rest of the assignment as described in Deliverables.
References and More Information
  1. Luhn algorithm: Wikipedia article
  2. Digit sum: Wikipedia article
  3. Digital root: Wikipedia article
  4. Credit Cards: DataGenetics blog post
  5. Frequently Asked Questions: Credit Card Generator
  6. Luhn Number Checksum: Verify numbers or calculate checksum

Image
Image source: my car

Project 3: Carbon Pains

Climate change is causing new weather patterns that will cause worse storms, droughts, floods, heat waves, deadly wildfires, stronger hurricanes, and sea level rise that will all affect us locally and throughout the world [1]. Human activities are the primary cause of climate change through the release of greenhouse gases such as C02, Methane, nitrous oxide, and Chlorofluorocarbons [2, 3]. Greenhouse gas (GHG) emissions from transportation account for about 29 percent of total U.S. GHG emissions, making it the largest contributor of U.S. GHG emissions [4].

One way to reduce GHG emissions is electric cars and trucks. In this project we compare the GHG emissions of traveling 100 miles in both a gas-powered and an electric-powered car.

Background Information

To calculate the carbon emissions of a gas car, we first need to calculate the gallons of gas consumed to travel the distance of 100 miles. This calculation is simply 100 miles / miles-per-gallon (MPG) of the car. Then we multiply the gallons consumed by the amount of carbon produced when consuming a gallon of gasoline.

Gallons = 100/MPG

The EPA says that burning each gallon of gas emits 19.64 pounds of CO2 [5]. This number does NOT include the carbon produced when extracting or refining the gasoline. One may wonder how a gallon of gasoline can produce almost 20 pounds of carbon dioxide. The answer is that the carbon atoms combine with the oxygen in the air to produce energy and CO2, increasing the weight of the carbon by 3.7 times [6].

CO2 = Gallons * 19.64

Electric cars are rated by the EPA using miles per gallon gasoline equivalent (MPGe). For electric vehicles, the EPA has determined that 33.7 kilowatt hours (kWh) of electricity is energy-equivalent to one gallon of gasoline. Thus to calculate the carbon emissions of an electric car, we first calculate the kWh consumed per mile, which is simply 33.7 / MPGe. Then we multiply by the amount of CO2 created to produce a kWh of electricity. California emits 0.474 lbs of CO2 per kWh generated [7], or 0 with solar panels.

CO2 = 33.7/MPGe * .474 * 100

Project Specifications
  1. Write a program to calculate the CO2 emitted driving 100 miles in a gas-powered car versus the same distance in an electric car.
  2. Name the source code file for this project carco2.cpp and include all your code in this 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, as shown in the Example Run below:
    1. Efficiency of the gas powered car in miles per gallon (MPG)
    2. Efficiency of the electric car in miles per gallon equivalent (MPGe)
  4. Use the default formatting and precision for the numbers.

    Ignore significant figures at this time and 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, including the same order of input and wording of the output, for you to receive full credit. For the input shown you must get the same output. However, the output numbers must change if the inputs are different.
    Gas vs. Electric Car CO2 Emissions
    
    Enter the fuel efficiency of the gas car in MPG: 24.7
    Enter the energy efficiency of electric car in MPGe: 112
    
    Carbon emitted traveling 100 miles in gas car: 79.5142 pounds
    Carbon emitted traveling 100 miles in electric car: 14.2623 pounds
    
    Gas vs. Electric Car CO2 Emissions
    
    Enter the fuel efficiency of the gas car in MPG: 50
    Enter the energy efficiency of electric car in MPGe: 123
    
    Carbon emitted traveling 100 miles in gas car: 39.28 pounds
    Carbon emitted traveling 100 miles in electric car: 12.9868 pounds
    

    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. Note that the MPGe of 112 is for a Nissan Leaf and the 123 is for a Tesla Model 3.

  6. After displaying the output, exit the program.
  7. Submit this project with the rest of the assignment as described in Deliverables.
Hints:
  • Get started by working though the steps by hand for calculating the CO2 emitted for traveling 100 miles in gas powered car. Once you understand those steps, type them out so you can translate them to C++.
  • Once you understand the gas powered car, review how to calculate CO2 for the electric-powered car from the project Background Information.
References and More Information
  1. The Effects of Climate Change: from NASA scientists
  2. The Causes of Climate Change: from NASA scientists
  3. Summary for Policymakers: IPCC's Fifth Assessment Report dated 2/2018
  4. Carbon Pollution from Transportation: from EPA scientists
  5. How much carbon dioxide is produced by burning gasoline and diesel fuel? 19.64 lbs CO2 per gallon
  6. How can a gallon of gasoline produce 20 pounds of carbon dioxide? by combining with the oxygen in the air.
  7. California Electricity Profile 2017: shows 0.474 lbs per kWh in 2017 (latest available), retrieved 1/10/2019.
  8. All-Electric Vehicles: why electric vehicles are more efficient--from the official U.S. government source for fuel economy information.

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 equation derived from mathworks.cpp making use of at least two of the inpu5 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 equation in a file named xcmathwork.cpp.
    2. Describe what the equation is used for in your README.txt file.
    3. Include the data input section of the original mathwork.cpp file. Note that if you do not use all the input variables in your equation 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 equations by assigning the solution to a unique output variable.
    5. Follow the output of the previous equations by labeling the equation with a cout statement displaying the label Equation6 followed by the value assigned to the unique variable when entering the example values  1.2 3 4  and then the equation result itself, like:
      Equation6 (42): 42
      Equation6 (42): 210
  2. Describe in your README.txt which equations 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 1 for the second number `b`.

  3. Look up constant variables in the textbook (p.39) and declare and use constant numbers in carco2.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)
    • 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. luhn.cpp
  5. carco2.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: September 12 2019 @16:38:04