Solution Manual for Problem Solving with C++, 10th Edition

Solution Manual for Problem Solving with C++, 10th Edition simplifies tough problems, making them easier to understand and solve.

Seller Steve
Contributor
4.3
80
9 months ago
Preview (31 of 956 Pages)
100%
Purchase to unlock

Page 1

Solution Manual for Problem Solving with C++, 10th Edition - Page 1 preview image

Loading page image...

INSTRUCTOR’S RESOURCEGUIDESOLUTIONS TO PROGRAMMING PROJECTSTO ACCOMPANYPROBLEMSOLVINGWITHC++TenthEditionWalter SavitchUNIVERSITY OF CALIFORNIA, SAN DIEGO

Page 2

Solution Manual for Problem Solving with C++, 10th Edition - Page 2 preview image

Loading page image...

Page 3

Solution Manual for Problem Solving with C++, 10th Edition - Page 3 preview image

Loading page image...

ContentsPrefaceChapter 1 Introduction to Computers and C++ ProgrammingChapter 2 C++ BasicsChapter 3 More Flow of ControlChapter 4 Procedural Abstraction and Functions that Return a ValueChapter 5 Functions for all SubtasksChapter 6 I/O Streams as an Introduction to Objects and ClassesChapter 7 ArraysChapter 8 Strings and VectorsChapter 9 Pointers and Dynamic ArraysChapter 10 Defining ClassesChapter 11 Friends, Overloaded Operators, and Arrays in ClassesChapter 12 Separate Compilation and NamespacesChapter 13 Pointers and Linked ListsChapter 14 RecursionChapter 15 InheritanceChapter 16 Exception HandlingChapter 17TemplatesChapter 18 Standard Template Libraryand C++11

Page 4

Solution Manual for Problem Solving with C++, 10th Edition - Page 4 preview image

Loading page image...

PrefaceThis is a document that is meant to be a supplement the text for the instructor. There is adiscussion 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 differentsolutions that correspond to different paths through the book. Thetest bank contains25 to 50 testquestions 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 programmingproblems. 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 howto do any problem, and any book will necessarily choose a subset to present. Our author has madesuch a set of choices. I have also made what I hope is a complementary set of choices for thisInstructor'sresource Manual. I am striving to produce a complementary document to the text, adocument for the instructor, but I necessarily will do some things differently. Please do not holdthe student responsible for what I have put here. The reader of this document must note that it isnecessary to read the text, as that is what the student has to work with. In spite of our efforts atconsistency of content and style, there will be some variance between some of the presentation hereand the presentation in the text.The code has been compiled and tested with g++ (gcc4.8.4)andVisual Studio C++ .NET 2017.Much of the code will work onVisual Studio C++ 6.0 updated to service pack 6but a newercompiler is recommended that is compliant with C++11. The text uses only mainstream features ofC++, consequently, most compilers will compile the code and produce output that does not differsignificantly from the results presented here. We have attempted to supply warnings where any ofthese compilers gives trouble.

Page 5

Solution Manual for Problem Solving with C++, 10th Edition - Page 5 preview image

Loading page image...

5Instructor's Resource ManualforSavitch,Problem Solving with C++Chapter 1Introduction to Computers and C++ ProgrammingThis document is intended to be a resource guide for instructors using Savitch, Problem Solving withC++.This guide follows the text chapter by chapter. Each chapter of this guide contains thefollowing sections:1. Solutions to, and remarks on, selected Programming Projects2. Outline of topics in the chapter3. General remarks on the chapterSolutions and remarks on selected Programming ProjectsThese programming exercises are intended to help familiarize the student with the programmingenvironment. Solutions are very system dependent. Consequently,onlytwosolutionsareprovidedfor the programming projects in this chapter.ProgrammingProject3.Changecalculator***********************************************************************//Ch1ProgrammingProject3.cpp////Thisprogramcalculatesthemonetaryvalueofanumberof//quarters,dimes,andnickels.//***********************************************************************#include<iostream>usingnamespacestd;//====================//mainfunction//====================intmain(){intquarters,dimes,nickels,total;//Inputcoinscout<<"Enternumberofquarters."<<endl;cin>>quarters;

Page 6

Solution Manual for Problem Solving with C++, 10th Edition - Page 6 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 16cout<<"Enternumberofdimes."<<endl;cin>>dimes;cout<<"Enternumberofnickels."<<endl;cin>>nickels;//Calculateandoutputtotaltotal=(quarters*25)+(dimes*10)+(nickels*5);cout<<"Themonetaryvalueofyourcoinsis"<<total<<"cents."<<endl;return0;}Programming Project 4. Distance in freefall//Ch1ProgrammingProject4.cpp//Thisprogramallowstheusertoenteratimeinseconds//andthenoutputshowfaranobjectwoulddropifitis//infreefallforthatlengthoftime#include<iostream>usingnamespacestd;intmain(){intACCELERATION=32;//Declareintegervariablesforthetimeanddistance.Alater//chapterwilldescribevariablesthatcanholdnon-integernumbers.inttime,distance;//Prompttheusertoinputthetimecout<<"Enterthetimeinseconds,thattheobjectfalls:";cin>>time;//Computethedistancedistance=ACCELERATION/2*time*time;cout<<"\nTheobjectwillfall"<<distance<<"feetin"<<time<<"seconds.\n";return0;}Outline of Topics in the Chapter 11.1 Computer Systems1.2 Programming and Problem-Solving1.3 Introduction to C++

Page 7

Solution Manual for Problem Solving with C++, 10th Edition - Page 7 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 171.4 Testing and DebuggingSuggested course outlines:There seem to be three major approaches to teaching C++ as the first course in programming. In theone approach, classes and objects are done very early, frequently with a library of some sort thatmust be used with the text. In another, all of the ANSI C subset of C++ is covered prior to evenmentioning 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 incomputing. Topics beyond Chapter 11 may be studied as time permits.Daydays allotted11Startup business2-32Chapter 1: Introduction to Computers4-85Chapter 2: C++ Basics. If the students have programming experience, the timespent can be significantly reduced.9-113Chapter 3:Flow of control12-143Chapter 4: Procedural AbstractionTest 116-183Chapter 5: Functions for all subtasks19-224Chapter 6: I/O Streams23-275Chapter 7: ArraysTest 229-324Chapter 8: Strings and VectorsChapter 9: Pointers and Dynamic Arrays33-375Chapter 10: Classes38-413Chapter 11: Friends and Overloaded OperatorsTest 35Chapter 12 Separate compilation and namespaces3Chapter 13 Pointers and Linked Lists3Chapter 14: Recursion3Chapter 15: Inheritance3Chapter 16: Exception Handling3Chapter 17: Templates2Chapter 18: Standard Template Libraryand C++11Reorderings:The author suggests a reordering in the preface that allow almost all of ANSI C (with the tighterC++ type-checking) to be covered before classes. Several variants on this reordering that allowclasses a bit earlier are presented in the text. The author describes interdependency of the chaptersin the preface of the text. Other reorderings are certainly possible.

Page 8

Solution Manual for Problem Solving with C++, 10th Edition - Page 8 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 18Chapter 1:The student should do all the programming assignments in this chapter. These teach the locallyavailable program development system and familiarize the student with some of the morecommon compiler errors. Error messages are quite specific to the compiler being used. It is veryimportant that the student learn these ideas as early as possible.Outline of topics in the chapter:1.1 Computer Systems1.2 Programming and Problem-Solving1.3 Introduction to C++1.4 Testing and DebuggingGeneral remarks on the chapterThis chapter serves as an introduction to computers and the language of computers for thosestudents who have no computer experience. The terminology is very important. Many studentsonly want to learn how the programming language works, and seem to be unhappy when theyfind that they are required to learn the terminology associated with the language. The studentswho 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 codingbegins. There are instances where several man-years of work have gone into software before asingle line of code was written.Emphasize the importance of the problem-solving phase of program design. This will save thestudent work in the long run. It is further important to emphasize that the problem definition andalgorithm design phases may need correcting once the actual coding and testing is in process. Thisis true even if the algorithm was carefully desktop tested. Emphasize that the program designprocess 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 taketo finish. My students insist on learning this the hard way. The algorithm design can be given aboost by dividing the problem definition into INPUT, PROCESS, OUTPUT phases. The algorithmwill be primarily concerned with PROCESS, but frequently just getting information into thecomputer, or out of the computer in a desirable format is a significant part of the task, if not thewhole problem.In the text, Section 1.4, subsection "Kinds of Program Errors", there is a discussion of compiler errormessages. The error message from g++ when the wrong operator<<or>>is used for input oroutput, is something like errormessage.cpp:8: no match for `_IO_ostream_withassign & >> int.Thepoint is that compiler error messages are not clear, and anything your can do to help students toassociate error messages with errors that cause them will help the student to gain some intuition indebugging based on compiler messages.

Page 9

Solution Manual for Problem Solving with C++, 10th Edition - Page 9 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 19Encourage students to put only one statement per line. When errors are made, as they inevitablyare, the compiler is better able to tell us which is the offending statement. The cost is little for theconvenience gained in ability to find errors. The student should take compiler warningsto heart.Ifthe compiler warns about something, and the student is not absolutely certain what the message iswarning about, the student should treat the warning like the error that it probably is. The bottomline is that all warnings (in the first course, at least) should be treated as errors. Compilers varywith respect to what is reported as an error and what is reported with a warning. The GNU projectC++ compiler, g++ is more permissiveby default. Encourage your students to compile usingg++-W-Wall--pedantic file.cppThis provides error messages that are close to thelintC-code checker.GNU g++4.7andVisual Studio 2013 very nearly meet the C++11Standard. With g++ you mayneed to add thestd=c++11 flag to compile with C++11.The student should be encouraged to ask the compiler questions about the C++ language, to createexamples and to actually test the questions on the computer. The compiler is the final authority onthe version of the languagethat the compiler accepts, regardless of the ISO Standard. An example isPractice Program6, where the student is asked to type in a simple program, then test the effect ofdeliberately introducing common errors.

Page 10

Solution Manual for Problem Solving with C++, 10th Edition - Page 10 preview image

Loading page image...

[Pick the date][CHAPTER 2]1Chapter 2C++ Basics1. Solutions to thePractice Programs and Programming Projects:Practice Program1. Metric-English units ConversionA metric ton is 35,273.92 ounces. Write a C++ program to read the weight of a boxof cereal in ounces then output this weight in metric tons, along with the numberof boxes to yield a metric ton of cereal.Design: To convert 14 ounces (of cereal) to metric tons, we use the 'ratio of units' totell us whether to divide or multiply:1metric tons14 ounces **= 0.000397 metric tons35,273ouncesThe use of units will simplify the determination of whether to divide or tomultiply in making a conversion. Notice that ounces/ounce becomes unit-less, sothat we are left with metric ton units. The number of ounces will be very, verymuch larger than the number of metric tons. It is then reasonable to divide thenumber of ounces by the number of ounces in a metric ton to get the number ofmetric tons.Now let metricTonsPerBox be the weight of the cereal box in metric tons. LetouncesPerBox the be the weight of the cereal box in ounces. Then in C++ theformula becomes:

Page 11

Solution Manual for Problem Solving with C++, 10th Edition - Page 11 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 22constdoubleouncesPerMetric_ton = 35272.92;metricTonsPerBox = ouncesPerBox / ouncesPerMetricTon;This is metric tons PER BOX, whence the number of BOX(es) PER metric tonshould 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>usingnamespace std;constdoubleouncesPerMetricTon = 35272.92;intmain(){doubleouncesPerBox, metricTonsPerbox,boxesPerMetricTon;charans = 'y';while( 'y' == ans || 'Y' == ans ){

Page 12

Solution Manual for Problem Solving with C++, 10th Edition - Page 12 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 23cout << “enter the weight in ounces of your”<< “favorite cereal:” <<endl;cin >> ouncesPerBox;metricTonsPerbox =ouncesPerBox / ouncesPerMetricTon;boxesPerMetricTon = 1 / metricTonsPerbox;cout << "metrictons 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;}return0;}A sample run follows:enterthe weight in ounces of your favorite cereal:14metric tons per box = 0.000396905boxesto yield a metricton = 2519.49Yory continues, any other characters terminates.yenterthe weight in ounces of your favorite cereal:20metric tons per box = 0.000567007

Page 13

Solution Manual for Problem Solving with C++, 10th Edition - Page 13 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 24boxesto yield a metricton = 1763.65Yory continues, any other characters terminates.nPractice Program 2 : Babylonian Algorithm//***********************************************************************//Chapter2PracticeProgram2////Thisprogramcomputesthesquarerootofanumbern//usingtheBabylonianalgorithm.//***********************************************************************#include<iostream>usingnamespacestd;//====================//mainfunction//====================intmain(){doubleguess;doublepreviousguess;doublen;doubler;//Inputnumbertocomputethesquarerootofcout<<"Enternumbertocomputethesquarerootof."<<endl;cin>>n;//Initialguess,althoughnotethisdoesn’tworkforthenumber1previousguess=n;guess=n/2;//Repeatuntilguessiswithin1%ofthepreviousguesswhile(((previousguess-guess)/previousguess)>0.01){previousguess=guess;r=n/guess;guess=(guess+r)/2;}cout<<"Theestimateofthesquarerootof"<<n<<"is"<<guess<<endl;

Page 14

Solution Manual for Problem Solving with C++, 10th Edition - Page 14 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 25return0;}Practice Program 3 : Treadmill Speed//**********************************************************************//Ch2Proj13.cpp////ThisprograminputsaspeedinMPHandconvertsitto//MinutesandSecondspermile,asmightbeoutputonatreadmill.//***********************************************************************#include<iostream>usingnamespacestd;//====================//mainfunction//====================intmain(){doublemilesPerHour;doublehoursPerMile;doubleminutesPerMile;doublesecondsPace;intminutesPace;//Inputmilesperhourcout<<"Enterspeedinmilesperhour:"<<endl;cin>>milesPerHour;//Computeinverse,whichishourspermilehoursPerMile=1.0/milesPerHour;//Converttominutespermilewhichis60seconds/hour*hoursPerMileminutesPerMile=60*hoursPerMile;//Extractminutesbyconvertingtoaninteger,while//truncatesanyvalueafterthedecimalpointminutesPace=static_cast<int>(minutesPerMile);//Secondsistheremainingnumberofminutes*60secondsPace=(minutesPerMile-minutesPace)*60;cout<<milesPerHour<<"milesperhourisapaceof"<<minutesPace<<"minutesand"<<secondsPace<<"seconds."<<endl;return0;}

Page 15

Solution Manual for Problem Solving with C++, 10th Edition - Page 15 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 26Practice Program 4 : MadLibs//**********************************************************************//Chapter2PracticeProgram4////Thisprogramplaysasimplegameof"MadLibs".//***********************************************************************#include<iostream>usingnamespacestd;//====================//mainfunction//====================intmain(){stringinstructorName;stringyourName;stringfood;intnum;stringadjective;stringcolor;stringanimal;cout<<"WelcometoMadLibs!Enteryourname:"<<endl;cin>>yourName;cout<<"Enteryourinstructor'sfirstorlastname."<<endl;cin>>instructorName;cout<<"Enterafood."<<endl;cin>>food;cout<<"Enteranumberbetween100and120."<<endl;cin>>num;cout<<"Enteranadjective."<<endl;cin>>adjective;cout<<"Enteracolor."<<endl;cin>>color;cout<<"Enterananimal."<<endl;cin>>animal;cout<<endl;cout<<"DearInstructor"<<instructorName<<","<<endl;cout<<endl;cout<<"IamsorrythatIamunabletoturninmyhomeworkatthistime."<<endl;cout<<"First,Iatearotten"<<food<<"whichmademeturn"<<color<<"and"<<endl;

Page 16

Solution Manual for Problem Solving with C++, 10th Edition - Page 16 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 27cout<<"extremelyill.Icamedownwithafeverof"<<num<<"."<<endl;cout<<"Next,my"<<adjective<<"pet"<<animal<<"musthave"<<"smelledtheremains"<<endl;cout<<"ofthe"<<food<<"onmyhomework,becauseheateit.Iam"<<"currently"<<endl;cout<<"rewritingmyhomeworkandhopeyouwillacceptitlate."<<endl;cout<<endl;cout<<"Sincerely,"<<endl;cout<<yourName<<endl;return0;}Practice Problem 5 : Volume of a Sphere//*********************************************************************//Chapter2PracticeProblem5////Re-writeaprogramusingthestyledescribedinthechapterfor//indentation,addcomments,anduseappropriatelynamedconstants.//***********************************************************************//FileName:volume.cpp//Author://EmailAddress://ProjectNumber:2.16//Description:Computesthevolumeofaspheregiventheradius//LastChanged:October6,2007#include<iostream>usingnamespacestd;intmain(){constdoublePI=3.1415;doubleradius,volume;//Prompttheusertoenteraradiuscout<<"Enterradiusofasphere."<<endl;cin>>radius;//Computeandprintthevolumevolume=(4.0/3.0)*PI*radius*radius*radius;cout<<"Thevolumeis"<<volume<<endl;

Page 17

Solution Manual for Problem Solving with C++, 10th Edition - Page 17 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 28return0;}Programming Project 1. Lethal DoseCertain artificial sweeteners are poisonous at some dosage level. It is desired toknow how much soda a dieter can drink without dying. The problem statementgives no information about how to scale the amount of toxicity from thedimensions of the experimental mouse to the dimensions of the dieter. Hence thestudent must supply this necessary assumption as basis for the calculation.This solution supposes the lethal dose is directly proportional to the weight of thesubject, henceweightOfDieterlethalDoseDieter = lethalDoseMouse *weightOfMouseThis 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 justkill the dieter, based on the lethal dose for a mouse in the lab. If the student hasproblems with grams and pounds, a pound is 454 grams.It is interesting that the result probably wanted is asafenumber of cans, while allthe data can provide is the minimum lethal number! Some students will probablyrealize this, but my experience is that most will not. I just weighed a can of dietpop and subtracted the weight of an empty can. The result is about 350 grams. Thelabel claims 355 ml, which weighs very nearly 355 grams. To get the lethal number

Page 18

Solution Manual for Problem Solving with C++, 10th Edition - Page 18 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 29of cans from the number of grams of sweetener, you need the number of grams ofsweetener in a can of pop, and the concentration of sweetener, which the problemassumes 0.1% , that is a conversion factor of 0.001.gramsSweetenerPerCan = 350 * 0.001 = 0.35 grams/cancans = lethalDoseDieter / (0.35 grams / can)//Ch2Programming Project 1//Input: lethal dose ofsweetener for a lab mouse, weights//ofmouse and dieter, and concentration of sweetener ina//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>usingnamespace std;constdoubleconcentration = .001; // 1/10 of 1 percentconstdoublecanWeight = 350;constdoublegramsSweetnerPerCan = canWeightconcentration;//unitsof grams/canintmain(){doublelethalDoseMouse, lethalDoseDieter,weightMouse,weightDieter; //units: gramsdoublecans;

Page 19

Solution Manual for Problem Solving with C++, 10th Edition - Page 19 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 210charans;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=lethalDoseMouseweightDieter/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

Solution Manual for Problem Solving with C++, 10th Edition - Page 20 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 211<< endl;cin >> ans;}while( 'y' == ans || 'Y' == ans );return0;}Atypical run follows:17:23:09:~/AW$ a.outEnterthe weight of themouse in grams15Enterthe lethal dose for the mouse in grams100Enterthe desired weight of the dieter, in grams45400Forthese parameters:mouseweight: 15 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThelethal dose in grams of sweetener is: 302667Lethal number of cans of pop: 864762Yory continues, any other character quitsyEnterthe weight of themouse in grams30Enterthe lethal dose for the mouse in grams100Enterthe desired weight of the dieter, in grams45400

Page 21

Solution Manual for Problem Solving with C++, 10th Edition - Page 21 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 212Forthese parameters:mouseweight: 30 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThelethal dose in grams of sweetener is: 151333Lethal number of cans of pop: 432381Yory continues, any other character quitsq17:23:56:~/AW$Programming Project 2. Pay IncreaseThe workers have won a 7.6% pay increase, effective 6 months retroactively. Thisprogram is to accept the previous annual salary, then outputs the retroactive paydue the employee, the new annual salary, and the new monthly salary. Allow userto repeat as desired. The appropriate formulae are:const double INCREASE = 0.076;newSalary = salary * (1 + INCREASE);monthly = salary / 12;retroactive = (salaryoldSalary)/2;The code follows://Ch2Programming Project 2//Given 6 mos retroactive 7.6% pay increase,//input salary//Output new annual andmonthly salaries, retroactive pay#include <iostream>

Page 22

Solution Manual for Problem Solving with C++, 10th Edition - Page 22 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 213usingnamespace std;constdouble INCREASE =0.076;intmain(){double oldSalary, salary, monthly, retroactive;char ans;cout << "Enter current annual salary." << endl<< "I'll returnnew annual salary, monthly ”<< “salary, andretroactive pay." << endl;cin>> oldSalary;//old annual salarysalary = oldSalary*(1+INCREASE);//new annual salarymonthly = salary/12;retroactive = (salaryoldSalary)/2;cout << "new annual salary " << salary << endl;cout << "new monthlysalary " << monthly << endl;cout << "retroactivesalary due: "<< retroactive << endl;return0;}17:50:12:~/AW$ a.outEntercurrent annual salary.100000I'llreturn new annual salary, monthly salary, andretroactive pay.newannual salary 107600newmonthly salary 8966.67

Page 23

Solution Manual for Problem Solving with C++, 10th Edition - Page 23 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 214retroactive salary due:3800Programming Project 3. Retroactive Salary// Modify program fromProgramming Project#2so 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 retroactiveincreasechar 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 salarycin >> numberOfMonths;salary = oldSalary * (1+INCREASE); //new annual salaryoldMonthly = oldSalary/12;monthly = salary/12;retroactive = (monthly-oldMonthly) * numberOfMonths;// retroactive = (salary-oldSalary)/2; // six monthsretroactive pay increase.cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;

Page 24

Solution Manual for Problem Solving with C++, 10th Edition - Page 24 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 215cout << "retroactive salary due: "<< retroactive << endl;return 0;}/*Typical runEnter current annual salary and a number of monthsfor which you wish to compute retroactive pay.I'll return new annual salary, monthly salary, and retroactivepay.120009new annual salary 12912new monthly salary 1076retroactive salary due: 684Press any key to continue*/Programming Project 6. PayrollThis problem involves payroll and uses the selection construct. A possiblerestatement: An hourly employee's regular payRate is$16.78/hour forhoursWorked <= 40 hours.IfhoursWorked > 40 hours, then(hoursWorked-40)is paid at an overtime premium rate of1.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 iswithheld for dependent health insurance.a) Write a program that, on a weekly basis, accepts hours worked then outputsgross pay, each withholding amount, and net (take-home) pay.b) Add 'repeat at user discretion' feature.

Page 25

Solution Manual for Problem Solving with C++, 10th Edition - Page 25 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 216I was unpleasantly surprised to find that with early GNU g++ , you cannot use aleading 0 (such as an SSN 034 56 7891) in a sequence of integer inputs. The gnuiostreams 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 thisrestriction.Otherwise, the code is fairly straight forward.//Programming Project 6//Payroll problem://Inputs: hoursWorked, number of dependents//Outputs: gross pay, each deduction, net pay////This is the 'repeat at user discretion' version//Outline://Ina real payroll program, each of these values would be//stored in a file after the payroll calculation was printed//toa report.////regular payRate = $10.78/hour for hoursWorked <= 40//hours.//IfhoursWorked > 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

Solution Manual for Problem Solving with C++, 10th Edition - Page 26 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 217//Ifnumber of dependents >= 3//$15 more is withheld for dependent health insurance.//#include <iostream>usingnamespace std;constdoublePAY_RATE =16.78;constdoubleSS_TAX_RATE = 0.06;constdoubleFedIRS_RATE = 0.14;constdoubleSTATE_TAX_RATE = 0.05;constdoubleUNION_DUES= 10.0;constdoubleOVERTIME_FACTOR = 1.5;constdoubleHEALTH_INSURANCE = 15.0;intmain(){doublehoursWorked, grossPay, overTime, fica,incomeTax, stateTax, union_dues, netPay;intnumberDependents, employeeNumber;charans;//set the output to two places, and force .00 for centscout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);//compute payrolldo{cout << "Enter employee SSN (digits only,”

Page 27

Solution Manual for Problem Solving with C++, 10th Edition - Page 27 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 218<< “ 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

Solution Manual for Problem Solving with C++, 10th Edition - Page 28 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 219cout << "Employee number: "<< employeeNumber << endl;cout << "hours worked: " << hoursWorked << endl;cout << "regularpay 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 << "FederalIncome 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 << "Computepay for another employee?”<< “ Y/y repeats, any other ends" << endl;

Page 29

Solution Manual for Problem Solving with C++, 10th Edition - Page 29 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 220cin >> ans;}while( 'y' == ans || 'Y' == ans );return0;}//A typical run:14:26:48:~/AW $ a.outEnteremployee SSN (digits only, no spaces or dashes)234567890Please the enter hours worked and number of employees.101Employee number: 234567890hoursworked: 10.00regular pay rate: 16.78grosspay: 167.80FICAtax withheld: 10.07Federal Income Tax withheld: 23.49StateTax withheld: 8.39Flabbergaster's Union Dues withheld: 10.00NetPay: 115.85Compute pay for anotheremployee? Y/y repeats, any otherendsyEnteremployee SSN (digits only, no spaces or dashes)987654321Please the enter hours worked and number of employees.10

Page 30

Solution Manual for Problem Solving with C++, 10th Edition - Page 30 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 2213Employee number: 987654321hoursworked: 10.00regular pay rate: 16.78grosspay: 167.80FICAtax withheld: 10.07Federal Income Tax withheld: 23.49StateTax withheld: 8.39Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00NetPay: 80.85Compute pay for anotheremployee? Y/y repeats, any otherendsyEnteremployee SSN (digits only, no spaces or dashes)123456789Please the enter hours worked and number of employees.453Employee number: 123456789hoursworked: 45.00regular pay rate: 16.78overtime hours worked: 5.00withovertime premium: 1.50grosspay: 797.05FICAtax withheld: 47.82Federal Income Tax withheld: 111.59StateTax withheld: 39.85

Page 31

Solution Manual for Problem Solving with C++, 10th Edition - Page 31 preview image

Loading page image...

SavitchInstructor’s Resource GuideProblem Solving w/C++, 10eChapter 222Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00NetPay: 552.79Compute pay for anotheremployee? Y/y repeats, any otherendsn14:28:12:~/AW $Programming Project 8. Installment Loan TimeNo down payment, 18 percent / year, payment of $50/month, payment goes first tointerest, balance to principal. Write a program that determines the number ofmonths it will take to pay off a $1000 stereo. The following code also outputs themonthly status of the loan.#include <iostream>usingnamespace std;//Chapter 2 Programming Project 8intmain(){double principal = 1000.;double interest, rate = 0.015;int months = 0;cout << "months\tinterest\tprincipal" << endl;while( principal >0 )
Preview Mode

This document has 956 pages. Sign in to access the full document!

Study Now!

XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat

Related Documents

View all