Solution Manual for Problem Solving with C++, 10th Edition
- Information Technology
- 956 pages
- Shared February 2025
- 80 downloads
Solution Manual for Problem Solving with C++, 10th Edition simplifies tough problems, making them easier to understand and solve.
Preview 31 of 956 pages
See the first 31 pages exactly as they appear in the document.
Page 1 Read page 1 as text
INSTRUCTOR’S RESOURCE GUIDE SOLUTIONS TO PROGRAMMING PROJECTS TO ACCOMPANY PROBLEM SOLVING WITH C++ Tenth Edition Walter Savitch UNIVERSITY OF CALIFORNIA, SAN DIEGO
Page 2 Page 3 Read page 3 as text
Contents Preface Chapter 1 Introduction to Computers and C++ Programming Chapter 2 C++ Basics Chapter 3 More Flow of Control Chapter 4 Procedural Abstraction and Functions that Return a Value Chapter 5 Functions for all Subtasks Chapter 6 I/O Streams as an Introduction to Objects and Classes Chapter 7 Arrays Chapter 8 Strings and Vectors Chapter 9 Pointers and Dynamic Arrays Chapter 10 Defining Classes Chapter 11 Friends, Overloaded Operators, and Arrays in Classes Chapter 12 Separate Compilation and Namespaces Chapter 13 Pointers and Linked Lists Chapter 14 Recursion Chapter 15 Inheritance Chapter 16 Exception Handling Chapter 17 Templates Chapter 18 Standard Template Library and C++11
Page 4 Read page 4 as text
Preface This is a document that is meant to be a supplement the text for the instructor. There is a discussion of the ideas in each chapter, teaching suggestions, and some supplementary ideas. There are solutions to many of the programming problems. Some problems have several different solutions that correspond to different paths through the book. The test bank contains 25 to 50 test questions with answers for each chapter. The questions are of both short answer (multiple choice, true false, fill in the blank) type as well as read - the - code questions and short programming problems. I urge that explanations to the short answer questions be required of the student. With regard to the content of this manual, it should be noted that C++ leaves many options on how to do any problem, and any book will necessarily choose a subset to present. Our author has made such a set of choices. I have also made what I hope is a complementary set of choices for this Instructor's resource Manual . I am striving to produce a complementary document to the text, a document for the instructor, but I necessarily will do some things differently. Please do not hold the student responsible for what I have put here. The reader of this document must note that it is necessary to read the text, as that is what the student has to work with. In spite of our efforts at consistency of content and style, there will be some variance between some of the presentation here and the presentation in the text. The code has been compiled and tested with g++ (gcc 4 . 8 . 4 ) and Visual Studio C++ .NET 20 1 7 . Much of the code will work on Visual Studio C++ 6.0 updated to service pack 6 but a newer compiler is recommended that is compliant with C++11 . The text uses only mainstream features of C++, consequently, most compilers will compile the code and produce output that does not differ significantly from the results presented here. We have attempted to supply warnings where any of these compilers gives trouble.
Page 5 Read page 5 as text
5 Instructor's Resource Manual for Savitch, Problem Solving with C++ Chapter 1 Introduction to Computers and C++ Programming This document is intended to be a resource guide for instructors using Savitch , Problem Solving with C++ . This guide follows the text chapter by chapter. Each chapter of this guide contains the following sections: 1. Solutions to, and remarks on, selected Programming Projects 2 . Outline of topics in the chapter 3 . General remarks on the chapter Solutions and remarks on selected Programming Projects These programming exercises are intended to help familiarize the student with the programming environment. Solutions are very system dependent. Consequently, only two solution s are provided for the programming projects in this chapter. Programming Project 3 . Change calculator *********************************************************************** // Ch1 Programming Proj ect 3 .cpp // // This program calculates the monetary value of a number of // quarters, dimes, and nickels. // *********************************************************************** #include <iostream> using namespace std; // ==================== // main function // ==================== int main() { int quarters, dimes, nickels, total; // Input coins cout << "Enter number of quarters." << endl; cin >> quarters;
Page 6 Read page 6 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 1 6 cout << "Enter number of dimes." << endl; cin >> dimes; cout << "Enter number of nickels." << endl; cin >> nickels; // Calculate and output total total = (quarters * 25) + (dimes * 10) + (nickels * 5); cout << "The monetary value of your coins is " << total << " cents." << endl; return 0; } Programming Project 4 . Distance in freefall // Ch1 Programming Proj ect 4 .cpp // This program allows the user to enter a time in seconds // and then outputs how far an object would drop if it is // in freefall for that length of time #include <iostream> using namespace std; int main() { int ACCELERATION = 32; // Declare integer variables for the time and distance. A later // chapter will describe variables that can hold non - integer numbers. int time, distance; // Prompt the user to input the time cout << "Enter the time in seconds, that the object falls: "; cin >> time; // Compute the distance distance = ACCELERATION/2 * time * time; cout << " \ nThe object will fall " << distance << " feet in " << time << " seconds. \ n"; return 0; } Outline of Topics in the Chapter 1 1.1 Computer Systems 1.2 Programming and Problem - Solving 1.3 Introduction to C++
Page 7 Read page 7 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 1 7 1.4 Testing and Debugging Suggested course outlines: There seem to be three major approaches to teaching C++ as the first course in programming. In the one approach, classes and objects are done very early, frequently with a library of some sort that must be used with the text. In another, all of the ANSI C subset of C++ is covered prior to even mentioning classes or objects. This text takes a third road that is more middle of the road. Here, enough of the control constructs and functions are covered prior to doing classes and objects. However, reorderings of the chapters are possible that allow any of these approaches. Here is a "classes early" course that follows the text closely. This outline assumes no background in computing. Topics beyond Chapter 11 may be studied as time permits. Day days allotted 1 1 Startup business 2 - 3 2 Chapter 1: Introduction to Computers 4 - 8 5 Chapter 2: C++ Basics. If the students have programming experience, the time spent can be significantly reduced. 9 - 11 3 Chapter 3: Flow of control 12 - 14 3 Chapt er 4: Procedural Abstraction Test 1 16 - 18 3 Chapter 5: Functions for all subtasks 19 - 22 4 Chapter 6: I/O Streams 23 - 27 5 Chapter 7: Arrays Test 2 29 - 32 4 Chapt er 8: Strings and Vectors Chapter 9: Pointers and Dynamic Arrays 33 - 37 5 Chapter 10: Classes 38 - 41 3 Chapter 11: Friends and Overloaded Operators Test 3 5 Chap ter 12 Separate compilation and namespaces 3 Chapter 13 Pointers and Linked Lists 3 Chapter 14: Recursion 3 Cha pter 15: Inheritance 3 Chapter 16: Exception Handling 3 Chapter 17: Templates 2 Chapter 18: Standard Template Library and C++11 Reorderings: The author suggests a reordering in the preface that allow almost all of ANSI C (with the tighter C++ type - checking) to be covered before classes. Several variants on this reordering that allow classes a bit earlier are presented in the text. The author describes interdependency of the chapters in the preface of the text. Other reorderings are certainly possible.
Page 8 Read page 8 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 1 8 Chapter 1: The student should do all the programming assignments in this chapter. These teach the locally available program development system and familiarize the student with some of the more common compiler errors. Error messages are quite specific to the compiler being used. It is very important that the student learn these ideas as early as possible. Outline of topics in the chapter: 1.1 Computer Systems 1.2 Programming and Problem - Solving 1.3 Introduction to C++ 1.4 Testing and Debugging General remarks on the chapter This chapter serves as an introduction to computers and the language of computers for those students who have no computer experience. The terminology is very important. Many students only want to learn how the programming language works, and seem to be unhappy when they find that they are required to learn the terminology associated with the language. The students who learn the terminology have less trouble by far with this course. Students should be given an indication of the amount of work that must be done before coding begins. There are instances where several man - years of work have gone into software before a single line of code was written. Emphasize the importance of the problem - solving phase of program design. This will save the student work in the long run. It is further important to emphasize that the problem definition and algorithm design phases may need correcting once the actual coding and testing is in process. This is true even if the algorithm was carefully desktop tested. Emphasize that the program design process is an 'iterative' process. You make a start, test, correct and repeat until you have a solution. It is a fact that the sooner the coding is started (on most problems), the longer the problem will take to finish. My students insist on learning this the hard way. The algorithm design can be given a boost by dividing the problem definition into INPUT, PROCESS, OUTPUT phases. The algorithm will be primarily concerned with PROCESS, but frequently just getting information into the computer, or out of the computer in a desirable format is a significant part of the task, if not the whole problem. In the text, Section 1.4, subsection "Kinds of Program Errors", there is a discussion of compiler error messages. The error message from g++ when the wrong operator << or >> is used for input or output, is something like errormessage.cpp:8: no match for ` _IO_ostream_withassign & >> int. The point is that compiler error messages are not clear, and anything your can do to help students to associate error messages with errors that cause them will help the student to gain some intuition in debugging based on compiler messages.
Page 9 Read page 9 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 1 9 Encourage students to put only one statement per line. When errors are made, as they inevitably are, the compiler is better able to tell us which is the offending statement. The cost is little for the convenience gained in ability to find errors. The student should take compiler warnings to heart. If the compiler warns about something, and the student is not absolutely certain what the message is warning about, the student should treat the warning like the error that it probably is. The bottom line is that all warnings (in the first course, at least) should be treated as errors. Compilers vary with respect to what is reported as an error and what is reported with a warning. The GNU project C++ compiler, g++ is more permissive by default. Encourage your students to compile using g++ - W - Wall -- pedantic file.cpp This provides error messages that are close to the lint C - code checker. GNU g++ 4.7 a nd Visual Studio 2013 v ery nearly meet the C++ 11 Standard . With g++ you may need to add the – std=c++11 flag to compile with C++11. The student should be encouraged to ask the compiler questions about the C++ language, to create examples and to actually test the questions on the computer. The compiler is the final authority on the version of the language that the compiler accepts , regardless of the ISO Standard. An example is Practice Program 6 , where the student is asked to type in a simple program, then test the effect of deliberately introducing common errors.
Page 10 Read page 10 as text
[Pick the date] [ CHAPTER 2 ] 1 Chapter 2 C++ Basics 1. Solutions to the Practice Programs and Programming Projects : Practice Program 1. Metric - English units Conversion A metric ton is 35,273.92 ounces. Write a C++ program to read the weight of a box of cereal in ounces then output this weight in metric tons, along with the number of boxes to yield a metric ton of cereal. Design: To convert 14 ounces (of cereal) to metric tons, we use the 'ratio of units' to tell us whether to divide or multiply: 1 metric tons 14 ounces * * = 0.000397 metric tons 35,273 ounces The use of units will simplify the determination of whether to divide or to multiply in making a conversion. Notice that ounces/ounce becomes unit - less, so that we are left with metric ton units. The number of ounces will be very, very much larger than the number of metric tons. It is then reasonable to divide the number of ounces by the number of ounces in a metric ton to get the number of metric tons. Now let metricTonsPerBox be the weight of the cereal box in metric tons. Let ouncesPerBox the be the weight of the cereal box in ounces. Then in C++ the formula becomes:
Page 11 Read page 11 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 2 const double ouncesPerMetric_ton = 35272.92; metricTonsPerBox = ouncesPerBox / ouncesPerMetricTon; This is metric tons PER BOX, whence the number of BOX(es) PER metric ton should be the reciprocal: boxesPerMetricTon = 1 / metricTonsPerBox; Once this analysis is made, the code proceeds quickly: //Purpose: To convert cereal box weight from ounces to // metric tons to compute number of boxes to make up a // metric ton of cereal. #include <iostream> using namespace std; const double ouncesPerMetricTon = 35272.92; int main() { double ouncesPerBox, metricTonsPerbox, boxesPerMetricTon; char ans = 'y'; while ( 'y' == ans || 'Y' == ans ) {
Page 12 Read page 12 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 3 cout << “enter the weight in ounces of your” << “favorite cereal:” <<endl; cin >> ouncesPerBox; metricTonsPerbox = ouncesPerBox / ouncesPerMetricTon; boxesPerMetricTon = 1 / metricTonsPerbox; cout << "metric tons per box = " << metricTonsPerbox << endl; cout << "boxes to yield a metric ton = " << boxesPerMetricTon << endl; cout << " Y or y continues, any other character ” << “terminates." << endl; cin >> ans; } return 0; } A sample run follows: enter the weight in ounces of your favorite cereal: 14 metric tons per box = 0.000396905 boxes to yield a metric ton = 2519.49 Y or y continues, any other characters terminates. y enter the weight in ounces of your favorite cereal: 20 metric tons per box = 0.000567007
Page 13 Read page 13 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 4 boxes to yield a metric ton = 1763.65 Y or y continues, any other characters terminates. n Practice Program 2 : Babylonian Algorithm //*********************************************************************** // Chapter 2 Practice Program 2 // // This program computes the square root of a number n // using the Babylonian algorithm. // *********************************************************************** #include <iostream> using namespace std; // ==================== // main function // ==================== int main() { double guess; double previousguess ; double n ; double r; // Input number to compute the square root of cout << "Enter number to compute the square root of." << endl; cin >> n; // Initial guess , although note this doesn’t work for the number 1 previousguess = n; guess = n /2; // Repeat until guess is within 1% of the previous guess while (((previousguess - guess) / previousguess) > 0.01) { previousguess = guess; r = n / guess; guess = (guess + r) / 2; } cout << "The estimate of the square root of " << n << " is " << guess << endl;
Page 14 Read page 14 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 5 return 0; } Practice Program 3 : Treadmill Speed // ********************************************************************** // Ch2Proj13.cpp // // This program inputs a speed in MPH and converts it to // Minutes and Seconds per mile, as might be output on a treadmill. // *********************************************************************** #include <iostream> using namespace std; // ==================== // main function // ==================== int main() { double milesPerHour ; double hoursPerMile ; double minutesPerMile ; double secondsPace; int minutesPace; // Input miles per hour cout << "Enter speed in miles per hour:" << endl; cin >> milesPerHour; // Compute inverse, which is hours per mile hoursPerMile = 1.0 / milesPerHour; // Convert to minutes per mile which is 60 seconds/hour * hoursPerMile minutesPerMile = 60 * hoursPerMile; // Extract minutes by converting to an integer, while // truncates any value after the decimal point minutesPace = static_cast<int>(minutesPerMile); // Seconds is the remaining number of minutes * 60 secondsPace = (minutesPerMile - minutesPace) * 60; cout << milesPerHour << " miles per hour is a pace of " << minutesPace << " minutes and " << secondsPace << " seconds. " << endl; return 0; }
Page 15 Read page 15 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 6 Practice Program 4 : MadLibs // ********************************************************************** // Chapter 2 Practice Program 4 // // This program plays a simple game of "Mad Libs". // *********************************************************************** #include <iostream> using namespace std; // ==================== // main function // ==================== int main() { string instructorName; string yourName; string food; int num; string adjective; string color; string animal; cout << "Welcome to Mad Libs! Enter your name: " << endl; cin >> yourName; cout << "Enter your instructor's first or last name." << endl; cin >> instructorName; cout << "Enter a food." << endl; cin >> food; cout << "Enter a number between 100 and 120." << endl; cin >> num; cout << "Enter an adjective." << endl; cin >> adjective; cout << "Enter a color." << endl; cin >> color; cout << "Enter an animal." << endl; cin >> animal; cout << endl; cout << "Dear Instructor " << instructorName << "," << endl; cout << endl; cout << "I am sorry that I am unable to turn in my homework at this time." << endl; cout << "First, I ate a rotten " << food << " which made me turn " << color << " and " << endl;
Page 16 Read page 16 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 7 cout << "extremely ill. I came down with a fever of " << num << "." << endl; cout << "Next, my " << adjective << " pet " << animal << " must have " << "smelled the remains " << endl; cout << "of the " << food << " on my homework, because he ate it. I am " << "currently " << endl; cout << "rewriting my homework and hope you will accept it late." << endl; cout << endl; cout << "Sincerely," << endl; cout << yourName << endl; return 0; } Practice Problem 5 : Volume of a Sphere //********************************************************************* // Chapter 2 Practice Problem 5 // // Re - write a program using the style described in the chapter for // indentation, add comments, and use appropriately named constants. // *********************************************************************** // File Name: volume.cpp // Author: // Email Address: // Project Number: 2.16 // Description: Computes the volume of a sphere given the radius // Last Changed: October 6, 2007 #include <iostream> using namespace std; int main() { const double PI = 3.1415; double radius, volume; // Prompt the user to enter a radius cout << "Enter radius of a sphere." << endl; cin >> radius; // Compute and print the volume volume = (4.0 / 3.0) * PI * radius * radius * radius; cout << " The volume is " << volume << endl;
Page 17 Read page 17 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 8 return 0; } Programming Project 1 . Lethal Dose Certain artificial sweeteners are poisonous at some dosage level. It is desired to know how much soda a dieter can drink without dying. The problem statement gives no information about how to scale the amount of toxicity from the dimensions of the experimental mouse to the dimensions of the dieter. Hence the student must supply this necessary assumption as basis for the calculation. This solution supposes the lethal dose is directly proportional to the weight of the subject, hence weightOfDieter lethalDoseDieter = lethalDoseMouse * weightOfMouse This program accepts weight of a lethal dose for a mouse, the weight of the mouse, and the weight of the dieter, and calculates the amount of sweetener that will just kill the dieter, based on the lethal dose for a mouse in the lab. If the student has problems with grams and pounds, a pound is 454 grams. It is interesting that the result probably wanted is a safe number of cans, while all the data can provide is the minimum lethal number! Some students will probably realize this, but my experience is that most will not. I just weighed a can of diet pop and subtracted the weight of an empty can. The result is about 350 grams. The label claims 355 ml, which weighs very nearly 355 grams. To get the lethal number
Page 18 Read page 18 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 9 of cans from the number of grams of sweetener, you need the number of grams of sweetener in a can of pop, and the concentration of sweetener, which the problem assumes 0.1% , that is a conversion factor of 0.001. gramsSweetenerPerCan = 350 * 0.001 = 0.35 grams/can cans = lethalDoseDieter / (0.35 grams / can) //Ch2 Programming Project 1 //Input: lethal dose of sweetener for a lab mouse, weights // of mouse and dieter, and concentration of sweetener in a // soda. //Output: lethal dose of soda in number of cans. //Assumption: lethal dose proportional to weight of subject // Concentration of sweetener in the soda is 1/10 percent #include <iostream> using namespace std; const double concentration = .001; // 1/10 of 1 percent const double canWeight = 350; const double gramsSweetnerPerCan = canWeight concentration; //units of grams/can int main() { double lethalDoseMouse, lethalDoseDieter, weightMouse, weightDieter; //units: grams double cans;
Page 19 Read page 19 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 10 char ans; do { cout << "Enter the weight of the mouse in grams" << endl; cin >> weightMouse; cout << "Enter the lethal dose for the mouse in“ << ”grams " << endl; cin >> lethalDoseMouse; cout << "Enter the desired weight of the dieter in” <<“ grams " << endl; cin >> weightDieter; lethalDoseDieter = lethalDoseMouse weight Dieter/weightMouse; cout << "For these parameters: \ nmouse weight: " << weightMouse << " grams " << endl << "lethal dose for the mouse: " << lethalDoseMouse << "grams" << endl << "Dieter weight: " << weightDieter << " grams " << endl << "The lethal dose in grams of sweetener is: " << lethalDoseDieter << endl; cans = lethalDoseDieter / gramsSweetnerPerCan; cout << "Lethal number of cans of pop: " << cans << endl; cout << "Y or y continues, any other character quits"
Page 20 Read page 20 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 11 << endl; cin >> ans; } while ( 'y' == ans || 'Y' == ans ); return 0; } A typical run follows: 17:23:09:~/AW$ a.out Enter the weight of the mouse in grams 15 Enter the lethal dose for the mouse in grams 100 Enter the desired weight of the dieter, in grams 45400 For these parameters: mouse weight: 15 grams lethal dose for the mouse: 100 grams Dieter weight: 45400 grams The lethal dose in grams of sweetener is: 302667 Lethal number of cans of pop: 864762 Y or y continues, any other character quits y Enter the weight of the mouse in grams 30 Enter the lethal dose for the mouse in grams 100 Enter the desired weight of the dieter, in grams 45400
Page 21 Read page 21 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 12 For these parameters: mouse weight: 30 grams lethal dose for the mouse: 100 grams Dieter weight: 45400 grams The lethal dose in grams of sweetener is: 151333 Lethal number of cans of pop: 432381 Y or y continues, any other character quits q 17:23:56:~/AW$ Programming Project 2 . Pay Increase The workers have won a 7.6% pay increase, effective 6 months retroactively. This program is to accept the previous annual salary, then outputs the retroactive pay due the employee, the new annual salary, and the new monthly salary. Allow user to repeat as desired. The appropriate formulae are: const double INCREASE = 0.076; newSalary = salary * (1 + INCREASE); monthly = salary / 12; retroactive = (salary – oldSalary)/2; The code follows: //Ch2 Programming Project 2 //Given 6 mos retroactive 7.6% pay increase, //input salary //Output new annual and monthly salaries, retroactive pay #include <iostream>
Page 22 Read page 22 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 13 using namespace std; const double INCREASE = 0.076; int main() { double oldSalary, salary, monthly, retroactive; char ans; cout << "Enter current annual salary." << endl << "I'll return new annual salary, monthly ” << “salary, and retroactive pay." << endl; cin >> oldSalary;//old annual salary salary = oldSalary*(1+INCREASE);//new annual salary monthly = salary/12; retroactive = (salary – oldSalary)/2; cout << "new annual salary " << salary << endl; cout << "new monthly salary " << monthly << endl; cout << "retroactive salary due: " << retroactive << endl; return 0; } 17:50:12:~/AW$ a.out Enter current annual salary. 100000 I'll return new annual salary, monthly salary, and retroactive pay. new annual salary 107600 new monthly salary 8966.67
Page 23 Read page 23 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 14 retroactive salary due: 3800 Programming Project 3 . Retroactive Salary // Modify program from Programming Project # 2 so that it // calculates retroactive // salary for a worker for a number of months entered by the user. //Given a 7.6% pay increase, //input salary //input number of months to compute retroactive salary //Output new annual and monthly salaries, retroactive pay #include <iostream> const double INCREASE = 0.076; int main() { using std::cout; using std::cin; using std::endl; double oldSalary, salary, monthly, oldMonthly, retroactive; int numberOfMonths; // number of months to pay retroactive increase char ans; cout << "Enter current annual salary and a number of months \ n" << "for which you wish to compute retroactive pay. \ n" << "I'll return new annual salary, monthly " << "salary, and retroactive pay." << endl; cin >> oldSalary;//old annual salary cin >> numberOfMonths; salary = oldSalary * (1+INCREASE); //new annual salary oldMonthly = oldSalary/12; monthly = salary/12; retroactive = (monthly - oldMonthly) * numberOfMonths; // retroactive = (salary - oldSalary)/2; // six months retroactive pay increase. cout << "new annual salary " << salary << endl; cout << "new monthly salary " << monthly << endl;
Page 24 Read page 24 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 15 cout << "retroactive salary due: " << retroactive << endl; return 0; } /* Typical run Enter current annual salary and a number of months for which you wish to compute retroactive pay. I'll return new annual salary, monthly salary, and retroactive pay. 12000 9 new annual salary 12912 new monthly salary 1076 retroactive salary due: 684 Press any key to continue */ Programming Project 6 . Payroll This problem involves payroll and uses the selection construct. A possible restatement: An hourly employee's regular payRate is $16.78/ hour for hoursWorked <= 40 hours. If hoursWorked > 40 hours , then (hoursWorked - 40) is paid at an overtime premium rate of 1.5 * payRate. FICA (social security) tax is 6% and Federal income tax is 14%. Union dues of $10/week are withheld. If there are 3 or more covered dependents, $15 more is withheld for dependent health insurance. a) Write a program that, on a weekly basis, accepts hours worked then outputs gross pay, each withholding amount, and net (take - home) pay. b) Add 'repeat at user discretion' feature.
Page 25 Read page 25 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 16 I was unpleasantly surprised to find that with early GNU g++ , you cannot use a leading 0 (such as an SSN 034 56 7891) in a sequence of integer inputs. The gnu iostreams library took the integer to be zero and went directly to the next input! You either have to either use an array of char, or 9 char variables to avoid this restriction. Otherwise, the code is fairly straight forward. // Programming Project 6 // P ay roll problem: //Inputs: hoursWorked, number of dependents //Outputs: gross pay, each deduction, net pay // //This is the 'repeat at user discretion' version //Outline: //In a real payroll program, each of these values would be //stored in a file after the payroll calculation was printed //to a report. // //regular payRate = $10.78/hour for hoursWorked <= 40 //hours. //If hoursWorked > 40 hours, // overtimePay = (hoursWorked - 40) * 1.5 * PAY_RATE . //FICA (social security) tax rate is 6% //Federal income tax rate is 14%. //Union dues = $10/week .
Page 26 Read page 26 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 17 //If number of dependents >= 3 // $15 more is withheld for dependent health insurance. // #include <iostream> using namespace std; const double PAY_RATE = 16.78; const double SS_TAX_RATE = 0.06; const double FedIRS_RATE = 0.14; const double STATE_TAX_RATE = 0.05; const double UNION_DUES = 10.0; const double OVERTIME_FACTOR = 1.5; const double HEALTH_INSURANCE = 15.0; int main() { double hoursWorked, grossPay, overTime, fica, incomeTax, stateTax, union_dues, netPay; int numberDependents, employeeNumber; char ans; //set the output to two places, and force .00 for cents cout.setf(ios::showpoint); cout.setf(ios::fixed); cout.precision(2); // compute payroll do { cout << "Enter employee SSN (digits only,”
Page 27 Read page 27 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 18 << “ no spaces or dashes) \ n”; cin >> employeeNumber ; cout << “Please the enter hours worked and number “ << “of employees.” << endl; cin >> hoursWorked ; cin >> numberDependents; cout << endl; if (hoursWorked <= 40 ) grossPay = hoursWorked * PAY_RATE; else { overTime = (hoursWorked - 40) * PAY_RATE * OVERTIME_FACTOR; grossPay = 40 * PAY_RATE + overTime; } fica = grossPay * SS_TAX_RATE; incomeTax = grossPay * FedIRS_RATE; stateTax = grossPay * STATE_TAX_RATE; netPay = grossPay - fica - incomeTax - UNION_DUES - stateTax; if ( numberDependents >= 3 ) netPay = netPay - HEALTH_INSURANCE; //now print report for this employee:
Page 28 Read page 28 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 19 cout << "Employee number: " << employeeNumber << endl; cout << "hours worked: " << hoursWorked << endl; cout << "regular pay rate: " << PAY_RATE << endl; if (hoursWorked > 40 ) { cout << "overtime hours worked: " << hoursWorked - 40 << endl; cout << "with overtime premium: " << OVERTIME_FACTOR << endl; } cout << "gross pay: " << grossPay << endl; cout << "FICA tax withheld: " << fica << endl; cout << "Federal Income Tax withheld: " << incomeTax << endl; cout << "State Tax withheld: " << stateTax << endl; if (numberDependents >= 3 ) cout << "Health Insurance Premium withheld: " << HEALTH_INSURANCE << endl; cout << "Flabbergaster's Union Dues withheld: " << UNION_DUES << endl; cout << "Net Pay: " << netPay << endl << endl; cout << "Compute pay for another employee?” << “ Y/y repeats, any other ends" << endl;
Page 29 Read page 29 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 20 cin >> ans; } while ( 'y' == ans || 'Y' == ans ); return 0; } //A typical run: 14:26:48:~/AW $ a.out Enter employee SSN (digits only, no spaces or dashes) 234567890 Please the enter hours worked and number of employees. 10 1 Employee number: 234567890 hours worked: 10.00 regular pay rate: 16.78 gross pay: 167.80 FICA tax withheld: 10.07 Federal Income Tax withheld: 23.49 State Tax withheld: 8.39 Flabbergaster's Union Dues withheld: 10.00 Net Pay: 115.85 Compute pay for another employee? Y/y repeats, any other ends y Enter employee SSN (digits only, no spaces or dashes) 987654321 Please the enter hours worked and number of employees. 10
Page 30 Read page 30 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 21 3 Employee number: 987654321 hours worked: 10.00 regular pay rate: 16.78 gross pay: 167.80 FICA tax withheld: 10.07 Federal Income Tax withheld: 23.49 State Tax withheld: 8.39 Health Insurance Premium withheld: 35.00 Flabbergaster's Union Dues withheld: 10.00 Net Pay: 80.85 Compute pay for another employee? Y/y repeats, any other ends y Enter employee SSN (digits only, no spaces or dashes) 123456789 Please the enter hours worked and number of employees. 45 3 Employee number: 123456789 hours worked: 45.00 regular pay rate: 16.78 overtime hours worked: 5.00 with overtime premium: 1.50 gross pay: 797.05 FICA tax withheld: 47.82 Federal Income Tax withheld: 111.59 State Tax withheld: 39.85
Page 31 Read page 31 as text
Savitch Instructor’s Resource Guide Problem Solving w/ C++, 10e Chapter 2 22 Health Insurance Premium withheld: 35.00 Flabbergaster's Union Dues withheld: 10.00 Net Pay: 552.79 Compute pay for another employee? Y/y repeats, any other ends n 14:28:12:~/AW $ Programming Project 8 . Installment Loan Time No down payment, 18 percent / year, payment of $50/month, payment goes first to interest, balance to principal. Write a program that determines the number of months it will take to pay off a $1000 stereo. The following code also outputs the monthly status of the loan. #include <iostream> using namespace std; // Chapter 2 Programming Project 8 int main() { double principal = 1000.; double interest, rate = 0.015; int months = 0; cout << "months \ tinterest \ tprincipal" << endl; while ( principal > 0 )
925 more pages in the full document
Unlock it once and it stays in your library, ready to chat with or turn into flashcards.
Unlock the full documentMore Information Technology study materials
See all
Exam GuidesTest Bank for Managing and Using Information Systems: A Strategic Approach, 7th Edition (Chapters 1-13)
Information Technology
452 pages149downloadsFeb 2025
Exam GuidesTest Bank for Essentials of MIS, 12th Edition
Information Technology
342 pages146downloadsFeb 2025
Exam GuidesA+ Guide to Hardware, 9th Edition Test Bank
Information Technology
116 pages142downloadsFeb 2025
Textbook GuidesSolution Manual for Essentials of System Analysis and Design, 4th Edition
Information Technology
282 pages140downloadsFeb 2025
Textbook GuidesGuide To Networking Essentials, 7th Edition Solution Manual
Information Technology
48 pages139downloadsFeb 2025
Past Exams2023-2024 SOPHOS FIREWALL V19.5 Practice Exam with Answers (75 Solved Questions)
Information Technology
7 pages134downloadsFeb 2025
Class NotesLecture Notes for CCNP Enterprise: Core Networking (ENCOR) v8 Lab Manual, 2nd Edition
Information Technology
1089 pages123downloadsFeb 2025
Class NotesLecture Notes for Adobe XD Classroom in a Book (2020 release)
Information Technology
66 pages118downloadsFeb 2025
Study this document with CramX
Once it is in your library, every tool can work from it.

