Patterns: Name Use: declare-define/build-use-destroy in the context of variables and objects
Raw Read; Verified Read (part 1)
Objects: type int, double; arithmetic and assignment
class string and its assignment operator
C++ language: identifiers and variables; types and classes: first look
cin, cout, endl;
x = RequestInt("prompt");
RequestString ("prompt", stringname)
System: project, compiler, running a program
overall structure of a program
read-compute-write, using int, double, and string
These exercises use the read-compute-write pattern to solve the problem. The first exercises illustrate raw read pattern, the rest use the IOTools functions to follow the verified read pattern. The programs use two built-in types of variables (int and double) and also objects in the class string. The programmer has to follow the declare-define-use pattern for the identifiers representing these entities.
The compute part is used to learn and practice the rules of both integer and decimal number arithmetic: the precedence rules, the conversion rules, and just the computational rules.
Read a problem carefully. Use a pencil and paper to try to solve the problem by hand. Repeat it for several instances to see what is the computational pattern. You can also use a calculator. Note what are the quantities you are working with. Note which are constants (they are the same for all instances of the problem) and which are the variables that depend on the user input. For example, when converting hours to minutes, 60 minutes in an hour is a constant, while the number of hours depends on the user input and is a variable. The result in minutes is also variable. Give meaningful names to the variables and for each variable decide whether it should be an integer (whole number), double (a decimal number), or a string (sequence of letters and other characters).
You can now write the statements that will declare these variables.
Now you are ready to work on the read-compute-execute pattern. Figure out first the program interface: what information will you need from the user and what information will the user receive in return. For example for the hours to minutes conversion, the user needs to supply the number of hours, the program will print the number of minutes in the given number of hours. You can now write the statements that will perform the reading and writing tasks.
Write out the sequence of computations. If you saved an intermediate result, you may use another variable to save it. Typically, you may need one or more variables to save the result. Write the code that will perform the computations, paying attention to the rules of arithmetic for the C++ language.
Compose the program, run it and check if the results are correct. Add comments as needed! Compare the results of several instances of the problem with your hand calculations and make sure they are the same. If they differ, make sure you know why. If you cannot figure out why, ASK SOMEONE!!!!
Save you work on a diskette and print your program.
Read with students solutions to problems 1, 2, 3, 4, and one more. Identify the steps in each program. Ask students to solve in small groups one of the later solved problems. Compare their solutions with the given ones.
Ask students to solve in small groups one of the easier practice exercises. Have them write the solutions on the board (concurrently) and compare the results.
Ask each group to pick one of the harder exercises and let those that are done present their solution on the board.
Each student should run all exercises that have been done in the class and the exercise that was started in their group.
Part 1: Solved problems
1. Ask user to type in two numbers. Print the product. Use raw read pattern.
Note: run it with incorrect input (not numbers) to see what happens.
2. Ask user to type in her name and her home town. Print 'Name from Town'. Use raw read pattern.
Note: Run the program with incorrect input (for example two word names) to see what happens. See what happens if you fail to supply input.
For all subsequent exercises use verified read pattern.
3. Ask the user to type in the length in feet and inches. Print the length in inches. Notice that with the verified read you can make mistakes in typing in the input data.
4. Ask the user to type in his name and his home town. Print 'Name from Town'. Notice that with the verified read you can use full names (first and last name) and cities with name like New York or Fall River.
5. Ask the user to type in name and age. Print 'Name is xx years old'.
6. Read in how many quarters, dimes, nickels, and pennies are there in a pile. Print how much money is there in dollars and cents.
7. You plan to visit a friend in another town. You know the distance in miles. Figure out how long will you have to drive at a given speed to get there.
Note that now it is your task to decide what is the input from the user and what are you going to print.
8. Your hike description gives you the starting and ending elevation (in feet) and the length of the hike (one way) in miles. Print how many feet did you climb for each mile of the hike.
9. You are going to compute your gross pay for the past week. Hours over 40 are paid at 1.5 times the regular hourly rate.
Note: This program uses a built-in function m = max(a, b); This function assigns to the variable m the value of the larger of the two quantities a or b.
10. Type in the race result as minutes and seconds. Type in the race distance in miles (with decimals). Print average speed per mile.
Part 2: Practice Problems - Easier
11. Ask the user to type in three numbers. Print the sum of the three numbers. Print the average of the three numbers. Use raw read pattern.
12. Modify the previous exercise by using the verified read pattern.
13. Ask the user to type in the name of a town and today's high temperature. Print "The high in Town today was xxx'. Use raw read pattern.
14. Modify the previous exercise by using the verified read pattern.
Use verified read pattern in all subsequent exercises.
15. Write the program that will compute the cost of a purchase of several equally priced items in a store. The user types in the number of items and the cost per item.
16. Modify the above program to add 5% sales tax to the total price.
17. Modify the above program so that the user types in also the name of the item. Also, add a message to the client 'Thank you for shopping with us.'.
18. Ask the user to type in how many one dollar, five dollar, ten dollar and twenty dollar bills does she have in her wallet. Print the total amount in the wallet.
19. Ask the user to type in the number of days, hours, and minutes, as well as his heart pulse rate. Print how many times did his heart beat during this time.
20. Write a program that will compute monthly gross pay for a salaried employee. The user types in the yearly salary base and a yearly elected contribution to pre-tax medical account. The program deducts 5% contribution to the retirement fund from the gross pay as well as the appropriate contribution to the medical account and prints the resulting gross pay.
Part 3: Practice Problems - Harder
21. One pound of flour equals four cups. Write a program for a cook, so she can enter the number of cups needed and the program will print the amount in pounds and ounces. Allow the user to enter 1.5 cups or 0.666 cups. Document your strategy in your program.
22. Write a program that will make change. The user enters number of cents due the customer (<100) and the program will print how many quarters, dimes, nickels, and pennies are needed. At this point you do not need to verify that the amount entered is indeed less than 100 and more than 0. You may want to explore how your program will perform with the erroneous input.
23. Recently a new world record for 400m has been set at 43.18 seconds. Write a program that will read the length of the race in meters and the time in seconds and fractions of seconds and print the average speed of the racer in miles per hour.
24. Write a program that will compute the number of hours and minutes of daylight. The user types in the time of the sunrise (am) and the time of the sunset (pm). Count only the time the sun is up (not the dawn and dusk hours).
25. Foresters compute the volume of the wood in a forest using estimations and computations.
(a) First they compute the height of a tree by measuring the angle from the ground to the top of the tree at a given distance from a tree. Write a program that will let the user type in the distance from the tree and the angle and will print the tree height. You decide what units you will use.
(b) Next, compute the volume of the tree trunk. Assume the tree is a cone of the given height, and with a given diameter of the trunk at the base.
(c) Finally, if you are given the average volume of a tree, the average number of trees per acre, and the size of the plot in acres, compute the volume of the wood in the forest.
26. You are getting ready for a scuba dive. You need to figure out how much oxygen will you need for a dive. You want to compute the volume of oxygen you breathe in during for the length of time you plan to be underwater. You need to know how many times you inhale in a minute and you need to measure your lung capacity. Remember that the air contains 20% oxygen.
Let the user type in the proposed duration of the dive, the respiration rate (inhalations per minute) and the lung capacity of the prospective diver (typically between 0.25 liters and 0.5 liters). Print how much oxygen will be needed.
27. In preparation for a homecoming weekend you plan to paint a float that will represent the earth globe. How much blue and how much yellow paint will you need for the orb of a given diameter? One pint of paint covers 75 square feet area. The earth surface is 2/3 water and 1/3 land. Modify the program to work for paints that cover more or less area.
28. For a home remodeling project you want to tile a floor with new tiles. Write a progam that will read the dimensions of the room (assume it is a rectangle) and the size of the square tiles to be used. Compute how many tiles will be needed. Of course, the tiles at two sides may need to be cut to fit.
29. Modify the previous program to compute the cost as well, given the cost of a box of 12 tiles. You cannot buy less than 12 tiles.
30. The computer screen is displayed by a beam that paints pixels as the beam sweeps across the lines of the CRT. The refresh rate tells us how many times per second is each pixel repainted. Compute the total number of pixels-paint operations per second for a given size screen resolution and the given refresh rate.
Using variables of the type int:
int x; //declare x as a variable of the type int - i.e. representing one whole number
x = 4; //initialize the value of the variable x to be 4
int x =4; //declare x as variable of the type int and initialize the value to be 4
x = 4 * 3 - 5/(2 + 3); //use variable x; assign a new value to it.
int y = 5 * x; //declare and define new int variable y; use variable x
The compiler destroys int variable automatically when appropriate.
Using objects in the class string:
string s; //declare s to represent a character string
s = "Hello World!"; //assigns the initial value to the string s
string a = "Hello";
string b = "World";
string s = a + " " + b + "!"; // declares s as string, initialized the initial value using previously defined strings a and b
Again, we do not have to worry about the destroy step.
~~~ more about other patterns