Solution Manual for Absolute C++, 6th Edition

Ace your coursework with Solution Manual for Absolute C++, 6th Edition, designed to simplify complex topics.

David Miller
Contributor
4.7
86
9 months ago
Preview (31 of 689 Pages)
100%
Purchase to unlock

Page 1

Solution Manual for Absolute C++, 6th Edition - Page 1 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualChapter 1C++ BasicsKey Termsfunctionsprogramintmain()return0identifiercase-sensitivekeyword or reserved worddeclarefloating-point numberfixed width integer typesautounsignedassignment statementuninitialized variableassigningintvalues todoublevariablesmixing typesintegers and Booleansliteral constantscientific notation or floating-point notationquotesC-stringstringescape sequenceconstmodifierdeclared constantmixing typesprecedence rulesinteger divisionthe % operatornegative integers in divisiontype casttype coercionincrement operatordecrement operatorv++ versus ++vcoutexpression in acoutstatementspaces in outputnewline characterdeciding between\nandendlformat fordoublevalues

Page 2

Solution Manual for Absolute C++, 6th Edition - Page 2 preview image

Loading page image...

Page 3

Solution Manual for Absolute C++, 6th Edition - Page 3 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manualmagic formulaoutputting money amountscerrcinhowcinworksseparate numbers with spaceswhen to comment#include,preprocessornamespaceusing namespaceBrief Outline1.1Introduction to C++Origins of theC++LanguageC++ and Object-Oriented ProgrammingThe Character of C++C++ TerminologyA Sample C++ Program1.2Variables, Expressions, and Assignment StatementsIdentifiersVariablesAssignment StatementsMore Assignment StatementsAssignment CompatibilityLiteralsEscape SequencesNaming ConstantsIntroduction to the string classArithmetic Operators and ExpressionsInteger and Floating-Point DivisionType CastingIncrement and Decrement Operators1.3 Console Input/OutputOutput Using coutNew Lines in OutputFormatting for Numbers with a Decimal PointOutput with cerrInput Using cin1.4Program StyleComments1.5Libraries and NamespacesLibraries and include DirectivesNamespaces

Page 4

Solution Manual for Absolute C++, 6th Edition - Page 4 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manual1.Introduction andTeaching SuggestionsThis chapter introduces the students to the history of theC++language and begins to tell themabout what types of programs can be written inC++as well as the basic structure of aC++program. During the discussions on compilation and running a program, care should be taken toexplain the process on the particular computer system that the students will be using, as differentcomputing/development environments will each have their own specific directions that will needto be followed.In the development of this instructor’s manual, a majority of the programs havebeen compiled using g++4.4.7on Ubuntu Linux, g++ 3.4 on cygwin, and Visual Studio .NET2013. There are significant differences between the development environments and sometimeson the compilers as well.This is especially the case with C++11 where command line optionsmay or may not be needed to compile, and some libraries may be unavailable for later sections(e.g. threading, regular expressions).Simple programming elements are then introduced, starting with simple variable declarations,data types,assignment statements, and eventually evolving into arithmetic expressions. Stringvariables are not introducedin detailuntil Chapter 9, butan introduction is given and could beelaborating upon if desired.If time allows, a discussion of how the computer stores data isappropriate. While some of the operations on the primitives are familiar to students, operationslike modulus(%) are usually not and require additional explanation. Also, the functionality ofthe increment and decrement operators requires attention. The issue of type casting is alsointroduced, which syntactically as well as conceptually can be difficult for students.Somestudents that have previously learned C may use the old form of type casting (e.g. (int)), butshould be encouraged to use the newer form (e.g. static_cast<int>).The section on programming style further introduces the ideas of conventions for naming ofprogrammatic entities and the use and importance of commenting source code. Commenting is askill that students will need to develop and they should begin commenting their code from thefirst program that they complete. Indentation is also discussed. However, many developmentenvironments actually handle this automatically.2.Key PointsCompiler.The compiler is the program that translates source code into a language that acomputer can understand. Students should be exposed to howcompilingworksin theirparticular development environment.If using an IDE, it is often instructive to show command-line compiling so students can a sense of a separate program being invoked to translate their codeinto machine code. This process can seem “magical” when a button is simply pressed in an IDEto compile a program.Syntax and Semantics.When discussing any programming language, we describe both therules for writing the language,i.e. itsgrammar, as well as the interpretation of what has beenwritten, i.e. its semantics. For syntax, we have a compiler that will tell us when we have made amistake. We can correct the error and try compiling again. However, the bigger challenge may

Page 5

Solution Manual for Absolute C++, 6th Edition - Page 5 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manuallie in the understanding of what the code actually means. There is no “compiler” for telling us ifthe code that is written will do what we want it to, and this is when the code does not do what wewant, it most often takes longer to fix than a simple syntax error.Names (Identifiers).C++has specific rules for how you can name an entity in a program.These rules are compiler enforced, but students should be able to recognize a correct or incorrectidentifier. Also, there are common conventions for howC++names its programming entities.Variablenames begin with alower case letterwhile constants are in all upper case. However,these conventions are not compiler enforced. The book and the source code forC++itself usethese conventions and it is helpful for students to understand that if they follow them, their codeis easier for others to read.Variable Declarations.C++requires that all variables be declared before they are used. Thedeclaration consists of the type of the variable as well as the name. You can declare more thanone variable per line.Assignment Statements with Primitive Types.To assign a value to a variable whose type is aprimitive, we use the assignment operator, which is the equals (=) sign. Assignment occurs byfirst evaluating the expression on the right hand side of the equals sign and then assigning thevalue to the variable on the left. Confusion usually arises for students when assigning the valueof one variable to another. Showing that x = y is not the same as y = x is helpful when trying toclear up this confusion.Initializing a Variable in a Declaration.We can and should give our variables an initial valuewhen they are declared. This is achieved through the use of the assignment operator. We canassign each variable a value on separate lines or we can do multiple assignments in one line.Assignment Compatibility.Normally, we can only assign values to a variable that are of thesame type as we declared the variable to be. For example, we can assign an integer value to aninteger variable. However, we can also assign acharvalue to an integer due to the followingordering:charshortintlongfloatdoubleValues on the left can be assigned to variables whose types are to the right. You cannot go in theother direction. In fact, the compiler will give an error if you do.However, you may receive acompiler warning message about loss of precision.What is Doubled?This discussion concerns how floating-point numbers are stored inside thecomputer. A related topic would be to show the conversion of these numbers into the format(e.g. IEEE 754 into two’s complement)that the computer uses.Escape Sequences.When outputting strings, the\character is used to escape the followingcharacter and interpret it literally. It is useful to use this to show how to output " or\along withuntypable characters, such as newlines or tabs.

Page 6

Solution Manual for Absolute C++, 6th Edition - Page 6 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualI/O with cin, cout, cerr.This discussion shows how to input values from the keyboard andoutput them to the screen. Under a Unix system it is easy to show the difference between coutand cerr by redirecting the output.Namespaces.This section illustrates how functions can exist within different namespaces.Students that have previously learned C sometimes have difficulty with namespaces. Someinstructors wish to avoid “using namespace std;” and instead prefer to start their programs onlyusing the constructs that are actually used (e.g. using std::cin;). The book starts using the entirenamespace but gravitates toward the latter toward the end of the book.Naming Constants.Program style is important and varies from one person to another.However, having programmatic style standards makes programs easier to read for everyone.One of these style points can be the naming of constants in the program. The convention that isintroduced is the one that is common toC++and the text.3.TipsError Messages.One of the most frustrating parts of learning how to program is learning tounderstand the error messages of the compiler. These errors, which are commonly called syntaxerrors, frustrate students. It is helpful to show some common error messages from the compilerso that students have a frame of reference when they see the errors again themselves. Alsoimportant for students to note is that even thoughC++states the line number that the erroroccurred on, it is not always accurate. Run-time errors occur when the program has been run.For this section, creating a simple statement that divides by zero can generate one such error.The last type of error, a logic error is one that is hardest to spot because on the surface theprogram runs fine, but does not produce the correct result.The difference between x++ and ++xcould be used here to illustrate a logic error.4.PitfallsUninitialized Variables.Variables that are declared but not assigned a value are uninitialized.It is good programming practice to always initialize your variables. It may be instructive tooutput the contents of uninitialized variables to show the unpredictable values they may contain.Uninitialized variables used in computation can cause errors in your program and the best way toavoid these errors is to always give variables an initial value. This can most easily be done rightwhen the variable is declared.Round-off Errors in Floating-Point Numbers.One of the places to show the fallibility ofcomputers is in the round-off errors that we experience when using floating point numbers. Thistopic relates to why the type is named double and also deals with the representation of floatingpoint numbers in the system. This problem occurs because not all floating-point numbers arefinite, a common example being the decimal representation of the fraction 1/3. Because we canonly store so many digits after the decimal points, our computation is not always accurate. A

Page 7

Solution Manual for Absolute C++, 6th Edition - Page 7 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manualdiscussion of when this type of round off error could be a problem would be appropriate tohighlight some of the shortcomings of computing.Division with Whole Numbers.InC++, all of the arithmetic operations are closed within theirtypes. Therefore, division of two integers will produce an integer, which will produce an answerthat most students do not expect. For example, the integer 1 divided by the integer 2 willproduce the integer 0. Students will expect 0.5. One way to get a floating-point answer out ofinteger division is to use typecasting. Another way is to force floating-point division by makingone of the integers a floating-point number by placing a “.0” at the end. Experimentation withthis issue is important to show the different results that can be obtained from integer division.Order of Evaluation.The order of evaluation of subexpressions is not guaranteed. Forexamplein(n + (++n))there will be a different result if ++n is evaluated first or second. Thebest advice is to avoid such scenarios. Precedence of operators is discussed in chapter 2.5.Programming Projects Answers1. Metric-English units ConversionA metric ton is35,273.92ounces. Write a C++ program to read the weight of a box of cerealin ounces then output this weight in metric tons, along with the number of boxes to yield a metricton of cereal.Design: To convert14ounces (of cereal) to metric tons, we use the 'ratio of units' to tell uswhether to divide or multiply:1metric tons14 ounces*= 0.000397 metric tons35,273.92ounceTheexplicituse of units will simplify the determination of whether to divide or to multiply inmaking a conversion. Notice that ounces/ounce becomes unit-less, so that we are left with metricton units. The number of ounces will be very, very much larger than the number of metric tons. Itis then reasonable to divide the number of ounces by the number of ounces in a metric ton to getthe number of metric tons.LetmetricTonsPerBoxbe the weight of the cereal contained in the box in metric tons, andletouncesPerBoxbe the weight of the cereal contained in the box in ounces. Then in C++ theformula becomes:constdouble ouncesPerMetricTon = 35272.92;metricTonsPerBox = ouncesPerBox/ouncesPerMetricTon;This is metric tons PER BOX, whence the number of BOX(es) PER metric ton should be thereciprocal of this number:

Page 8

Solution Manual for Absolute C++, 6th Edition - Page 8 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualboxesPerMetricTon = 1 / metricTonsPerBox;Once this analysis is made, the code proceeds quickly://Purpose: To convert cereal box weight from ounces to//metric tons and to compute number of boxes of cereal that//constitute a metric ton of cereal.#include <iostream>usingnamespace std;constdouble oncesPerMetricTon = 35272.92;intmain(){doubleouncesPerBox, metricTonsPerBox, boxesPerMetricTon;cout<< “enter the weight in ounces of your”<< “favorite cereal:” <<endl;cin>> ouncesPerBox;metricTonsPerBox =ouncesPerBox / oncesPerMetricTon;boxesPerMetricTon = 1 / metricTonsPerBox;cout<< "metric tons per box = "<< metricTonsPerBox << endl;cout<< "boxes to yield a metric ton = "<< boxesPerMetricTon << endl;return0;}A sample run follows:~/AW$a.outenterthe weight in ounces of your favorite cereal:14metrictons per box = 0.000396905boxesto yield a metric ton = 2519.49enterthe weight in ounces of your favorite cereal:2. Lethal DoseCertain artificial sweeteners are poisonous at some dosage level. It is desired to know how muchsoda a dieter can drink without dying. The problem statement gives no information about how toscale the amount of toxicity from the dimensions of the experimental mouse to the dimensions ofthe dieter. Hence the student must supply some more or less reasonable assumption as basis forthe calculation.

Page 9

Solution Manual for Absolute C++, 6th Edition - Page 9 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualThis solution supposes the lethal dose is directly proportional to the weight of the subject, hencelethal_dose_dieter = lethal_dose_mouse*weightofdieterweightofmouse____This program accepts weight of a lethal dose of sweetener for a mouse, the weight of the mouse,and the weight of the dieter, then 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 andpounds, a pound is 454 grams.It is interesting that the result probably wanted is asafenumber of cans, while all the data canprovide is the minimum lethal number. Some students will probably realize this, but myexperience is that most will not, or will not care. I just weighed a can of diet pop and subtractedthe weight of an empty can. The result is about 350 grams. The label claims 355 ml, whichweighs very nearly355 grams.To get the lethal number of cans from the number of grams ofsweetener, you need the number of grams of sweetener in a can of pop, and the concentration ofsweetener, which the problem assumes 0.1% , that is, a conversion factor of 0.001.gramsSweetenerPerCan = 350 * 0.001 = 0.35 grams/cancans = lethalDoseForDieter / (0.35 grams / can)//Input: lethal dose of sweetener for a lab mouse, weights//ofmouse and dieter, and concentration of sweetener in a//soda.//Output: lethal dose of soda as a 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;constdouble concentration = .001; // 1/10 of 1 percentconstdouble canWeight = 350;constdouble gramsSweetenerPerCan =canWeight *concentration; //units: grams/canintmain(){doublelethalDoseMouse, lethalDoseDieter,weightMouse, weightDieter; //units: gramsdoublecans;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”

Page 10

Solution Manual for Absolute C++, 6th Edition - Page 10 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manual<<“ 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 / gramsSweetenerPerCan;cout<< "Lethal number of cans of pop: "<< cans << endl;return0;}Atypical run follows:Enterthe weight of the mouse in grams15Enterthe lethal dose for the mouse in grams100Enterthe desired weight of the dieter, in grams45400Forthese parameters:mouseweight: 15 gramslethaldose for the mouse: 100 gramsDieterweight: 45400 gramsThelethal dose in grams of sweetener is: 302667Lethalnumber of cans of pop: 8647623. Pay IncreaseThe workers have won a 7.6% pay increase, effective 6 months retroactively. This program is toaccept the previous salary, then outputs the retroactive pay due the employee, the new annualsalary, and the new monthly salary. Allow user to repeat as desired. The appropriate formulaeare:newSalary = salary * ( 1 + INCREASE );monthly = salary / 12;retroactive = (newSalarysalary) / 2;

Page 11

Solution Manual for Absolute C++, 6th Edition - Page 11 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualThe code follows://Given6 months retroactive, 7.6% pay increase,//Input: old salary//Output: new annual and monthly salary, retroactive pay due#include <iostream>usingnamespace std;constdouble INCREASE = 0.076;intmain(){double oldSalary, salary, monthly, retroactive;charans;cout<< "Enter current annual salary." << endl<< "I'll return new annual salary, monthly ”<< “salary, and retroactive pay." << endl;cin>> oldSalary;salary = oldSalary * ( 1 + INCREASE );monthly = salary / 12;retroactive = (salaryoldSalary) / 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.outEntercurrent annual salary.100000I'llreturn new annual salary, monthly salary, and retroactivepay.new annual salary 107600newmonthly salary 8966.67retroactive salary due: 538004. Consumer LoanThis problem is an example where the student needs to have a solution in hand before going tothe computer. Algebra will solve the problem based on what is given. First compute the“discounted loan face value” in terms of the other things known:InterestRateandNoYearsToRun:AmountRecevied = FaceValuediscountDiscount = FaceValue * AnnualInterestRate*NoYearsToRun;AmountReceived =FaceValueFaceValue*AnnualInterestRate*NoYearsToRunThen ask them to solve forFaceValue:

Page 12

Solution Manual for Absolute C++, 6th Edition - Page 12 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualFaceValue =AmountReceived / (1AnnualInterestRate*NoYearsToRun)Writing a program for this will be easy.5. Occupancy of Meeting Room beyond file-law limits.Program reads the maximum occupancy, then the then the number of attendees. If the maximumhas been exceeded, announces either that the room has its maximum occupancy exceeded andhow many must leave, else it announces that the maximum has not been exceeded.This problem uses theif-elseillustrated in Display 1.1, and a one-sidedifstatement,//Maximum Occupancy#include <iostream>using namespace std;int main(){int maxOccupancy;int numberOccupants;cout << "Enter the Maximum occupancy for the room.\n";cin >> maxOccupancy;cout << maxOccupancy << endl;cout << "Enter the number of occupants of the room.\n";cin >> numberOccupants;cout << numberOccupants << endl;if(numberOccupants > maxOccupancy)cout << "ATTENTION: MAXIMUM OCCUPANCY EXCEEDED.\n"<< "THE LAW REQUIRES "<< numberOccupants-maxOccupancy<< " PERSONS TO LEAVE THE ROOM IMMEDIATELY\n";elsecout <<"The number of occupants does not exceed "<< "the legal maximum.\n";return 0;}/*A typical run is:Enter the Maximum occupancy for the room.250Enter the number of occupants of the room.375ATTENTION: MAXIMUM OCCUPANCY EXCEEDED.THE LAW REQUIRES 125 PERSONS TO LEAVE THE ROOM IMMEDIATELYAnother run:Enter the Maximum occupancy for the room.250Enter the number of occupants of the room.225The number of occupants does not exceed the legal maximum.*/

Page 13

Solution Manual for Absolute C++, 6th Edition - Page 13 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manual6. Overtime PayThis problem uses theif-elseillustrated in Display 1.1, and a one-sidedifstatement, whichis just anif-elsewith theelseclause omitted.//pay roll problem://Inputs: hoursWorked, number of dependents//Outputs: gross pay, each deduction, net pay////Outline:////regular payRate = $16.78/hour for hoursWorked <= 40 //hours.//For hoursWorked > 40 hours,//overtimePay = (hoursWorked-40) * 1.5 * payRate.//FICA (social security) tax rate is 6%//Federal income tax rate is 14%.//Union dues = $10/week .//If number of dependents >= 3//$35 more is withheld for dependent health insurance.//#include <iostream>using namespace std;const double PAYRATE = 16.78;const double SS_TAX_RATE = 0.06;const double FedIRS_RATE = 0.14;const double STATETAX_RATE = 0.05;const double UNION_DUES = 10.0;const double OVERTIME_FACTOR = 1.5;const double HEALTH_INSURANCE = 35.0;int main(){double hoursWorked, grossPay, overTime, fica,incomeTax, stateTax, netPay;int numberDependents, employeeNumber;//set the output to two places, and force .00 for centscout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);// compute payrollcout << "Enter employee SSN (digits only,"<< " no spaces or dashes)\n";cin >> employeeNumber ;cout << endl << employeeNumber << endl;cout << "Please enter hours worked\n";cin >> hoursWorked;cout << endl << hoursWorked << endl;cout << "Please enter number of dependants." << endl;cin >> numberDependents;cout << endl << numberDependents << endl << endl;if (hoursWorked <= 40 )

Page 14

Solution Manual for Absolute C++, 6th Edition - Page 14 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualgrossPay = hoursWorked * PAYRATE;elseoverTime =(hoursWorked-40) * PAYRATE * OVERTIME_FACTOR;if (hoursWorked > 40)grossPay = 40 * PAYRATE + overTime;fica = grossPay * SS_TAX_RATE;incomeTax = grossPay * FedIRS_RATE;stateTax = grossPay * STATETAX_RATE;netPay = grossPay-fica-incomeTax-UNION_DUES-stateTax;if (numberDependents >= 3)netPay = netPay-HEALTH_INSURANCE;//now print report for this employee:cout << "Employee number: "<< employeeNumber << endl;cout << "hours worked: " << hoursWorked << endl;cout << "regular pay rate: " << PAYRATE << endl;if (hoursWorked > 40)cout << "overtime hours worked: "<< hoursWorked-40 << endl;if (hoursWorked > 40)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;return 0;}/*Two typical runs follow:Enter employee SSN (digits only, no spaces or dashes)234567890234567890Please enter hours worked37.0037.00Please enter number of dependants.

Page 15

Solution Manual for Absolute C++, 6th Edition - Page 15 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manual11Employee number: 234567890hours worked: 37.00regular pay rate: 16.78gross pay: 620.86FICA tax withheld: 37.25Federal Income Tax withheld: 86.92State Tax withheld: 31.04Flabbergaster's Union Dues withheld: 10.00Net Pay: 455.64Enter employee SSN (digits only, no spaces or dashes)234567890234567890Please enter hours worked54.0054.00Please enter number of dependants.44Employee number: 234567890hours worked: 54.00regular pay rate: 16.78overtime hours worked: 14.00with overtime premium: 1.50gross pay: 1023.58FICA tax withheld: 61.41Federal Income Tax withheld: 143.30State Tax withheld: 51.18Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 722.69/*7. CaloriesOne way to measure the amount of energy that is expended during exercise is to use metabolicequivalents (MET). Here are some METS for various activities:Running 6 MPH:10 METSBasketball:8 METSSleeping:1 METThe number of calories burned per minute may be estimated using the formula:Calories/Minute = 0.0175METWeight(Kg)

Page 16

Solution Manual for Absolute C++, 6th Edition - Page 16 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualWrite a program that inputs a subject’s weight in pounds, the number of METS for an activity,and the number of minutes spent in that activity, and then outputs the estimate for total numberof calories burned. One kilogram is equal to 2.2 pounds.//calories.cpp//This program calculates the amount of energy expended//using the concept of metabolic equivalents.The formula//used is Calories/Minute = 0.0175 * MET * WeightInKilos//One Kg = 2.2 Pounds#include <iostream>#include <cstdlib>using namespace std;const double POUNDS_TO_KG = 1 / 2.2;// ======================//main function// ======================int main(){//// Variable declarationsdouble mets;double weight_lb;double mins;double weight_kg;double calories;cout << endl << "Welcome to the calorie calculator." << endl;//--------------------------------//-----ENTER YOUR CODE HERE-----//--------------------------------cout << "Enter your weight in pounds: " << endl;cin >> weight_lb;cout << "Enter the number of METS for the activity: " << endl;cin >> mets;cout << "Enter the number of minutes spent exercising: " << endl;cin >> mins;// Convert from pounds to kilogramsweight_kg = POUNDS_TO_KG * weight_lb;// Formula to compute caloriescalories = 0.0175 * mets * weight_kg * mins;// Output total caloriescout << "You burned an estimated " << calories << " calories."<< endl <<endl;

Page 17

Solution Manual for Absolute C++, 6th Edition - Page 17 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manual//--------------------------------//---------END USER CODE--------//--------------------------------8. BabylonianThe Babylonian algorithm to compute the square root of a numbernis as follows:1.Make aguessat the answer (you can pick n/2 as your initial guess).2.Computer = n / guess3.Setguess = (guess +r) / 24.Go back to step 2 for as many iterations as necessary. The more that steps 2 and 3 arerepeated, the closerguesswill become to the square root ofn.Write a program that inputs an integer forn, iterates through the Babylonian algorithm fivetimes, and outputs the answer as a double to two decimal places. Your answer will be mostaccurate for small values ofn.CodeMate Hints: Make guess a doubleCodeMate Hints: Typecast using static_cast<double>(n) described on page 23CodeMate Hints: See page 31 for the magic formula on setting the precision for outputtingdoubles.//babylonian.cpp////This program uses the Babylonian algorithm, using five//iterations, to estimate the square root of a number n.#include <iostream>#include <cstdlib>using namespace std;// ======================//main function// ======================int main(){//--------------------------------//-----ENTER YOUR CODE HERE-----//--------------------------------// Variable declarationsdouble guess;int n;double r;cout << endl << "This program makes a rough estimate for squareroots."<< endl;cout << "Enter an integer to estimate the square root of: " <<endl;cin >> n;

Page 18

Solution Manual for Absolute C++, 6th Edition - Page 18 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manual// Initial guessguess = static_cast<double>(n)/2;// First guessr = static_cast<double>(n)/ guess;guess = (guess+r)/2;// Second guessr = static_cast<double>(n)/ guess;guess = (guess+r)/2;// Third guessr = static_cast<double>(n)/ guess;guess = (guess+r)/2;// Fourth guessr = static_cast<double>(n)/ guess;guess = (guess+r)/2;// Fifth guessr = static_cast<double>(n)/ guess;guess = (guess+r)/2;// Code to set the precision to 2 decimal placescout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2);// Output the fifth guesscout << "The estimated square root of " << n << " is " << guess<< endl << endl;//--------------------------------//---------END USER CODE--------//--------------------------------9. CouponsThe video game machines at your local arcade output coupons depending upon how well youplay the game. You can redeem 10 coupons for a candy bar or 3 coupons for a gumball. Youprefer candy bars to gumballs. Write a program that inputs the number of coupons you win andoutputs how many candy bars and gumballs you can get if you spend all of your coupons oncandy bars first, and any remaining coupons on gumballs.CodeMate Hints: Use the % operator to compute the number of coupons remaining//coupons.cpp////This program computes the number of candy bars and gumballsyou//can get by redeeming coupons at an arcade.10 coupons is//redeemable for candy bars and 3 coupons for gumballs.You//would like as many candy bars as possible and only use//remaining coupons on gumballs.

Page 19

Solution Manual for Absolute C++, 6th Edition - Page 19 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manual#include <iostream>#include <cstdlib>using namespace std;// ======================//main function// ======================int main(){// Variable declarationsint num_coupons = 0;int num_coupons_after_candybars = 0;int num_coupons_after_gumballs = 0;int num_candy_bars = 0;int num_gumballs = 0;cout << endl << "Candy calculator.Enter number of coupons toredeem:"<< endl;////--------------------------------//-----ENTER YOUR CODE HERE-----//--------------------------------cin >> num_coupons;// Integer division below discards any remaindernum_candy_bars = num_coupons / 10;// Calculate remaining couponsnum_coupons_after_candybars = num_coupons % 10;// Calculate gumballsnum_gumballs = num_coupons_after_candybars / 3;// Calculate any leftover couponsnum_coupons_after_gumballs = num_coupons_after_candybars % 3;// Output the number of candy bars and gumballscout << "Your " << num_coupons << " coupons can be redeemed for" <<num_candy_bars << " candy bars and " <<num_gumballs << " gumballs with " <<num_coupons_after_gumballs << " coupons leftover."<< endl << endl;//--------------------------------//---------END USER CODE--------//--------------------------------10. Freefall

Page 20

Solution Manual for Absolute C++, 6th Edition - Page 20 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s ManualWrite a program that allows the user to enter a time in seconds and then outputs how far anobject would drop if it is in freefall for that length of time. Assume no friction or resistance fromair and a constant acceleration of 32 feet per second due to gravity. Use the equation:221distancetimeonaccelerati// Programming Project 1.10#include <iostream>using namespace std;int main(){cout << "Enter a time in seconds." << endl;int s;cin >> s;int distance;distance = (32 / 2) * (s * s);cout << "An object in freefall for " << s <<" seconds will fall " << distance <<" feet." << endl;// Type a key and enter to close the programchar c;cin >> c;}11. Time ConversionWrite a program thatinputs an integer that represents a length of time in seconds. The programshould thenoutput the number of hours, minutes, and seconds that corresponds tothat number ofseconds. For example, if the user inputs50391total secondsthen theprogram shouldoutput 13hours, 59 minutes, and 51 seconds.// Programming Project 1.11#include <iostream>using namespace std;int main(){cout << "Enter a time in seconds." << endl;int s;cin >> s;int hours, minutes, seconds;hours = s / 3600;minutes = (s % 3600) / 60;seconds = (s % 3600) % 60;cout << s << " total seconds is equivalent to " <<hours << " hours, " << minutes <<

Page 21

Solution Manual for Absolute C++, 6th Edition - Page 21 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manual" minutes, and " << seconds <<" seconds. "<< endl;// Type a key and enter to close the programchar c;cin >> c;}12. Ideal Body Weight EstimationA simple rule to estimate your ideal body weight is to allow 110 pounds for the first 5 feet of height and 5pounds for each additional inch. Write a program with a variable for the height of a person in feet and anothervariable for the additional inches and input values for these variables from the keyboard.Assume the personis at least 5 feet tall. For example, a person that is 6 feet and 3 inches tall would be represented with a variablethat stores the number 6 and another variable that stores the number 3. Based on these values calculate andoutput the ideal body weight.// Programming Project 1.12#include <iostream>using namespace std;int main(){int heightFeet = 5;int heightInches = 5;cout << "Your ideal bodyweightis";int weight = 110 + ((heightFeet-5)*12+ heightInches)* 5;cout << weight << " pounds."<<endl;return 0;}13. Lethal CaffeineScientists estimate that consuming roughly 10 grams of caffeine at once is a lethal overdose. Write a programthat inputs the number of milligrams of caffeine in a drink and outputs how many drinks it would take to kill aperson. A 12 ounce can of cola has approximately 34 mg of caffeine while a 16 ounce cup of coffee hasapproximately 160 mg of caffeine.//Programming Project 1.13#include <iostream>using namespace std;int main(){int mg;cout << "How many milligramsofcaffeine inthe drink?" <<endl;cin >>mg;// 10 grams to kill a personis10000mg

Page 22

Solution Manual for Absolute C++, 6th Edition - Page 22 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter 1,Instructor’s Manualint numDrinks = 10000 / mg;cout << "The number of drinksitwilltaketokillsomeoneis" <<numDrinks << " drinks." <<endl;return0;}

Page 23

Solution Manual for Absolute C++, 6th Edition - Page 23 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s ManualChapter2Flow of ControlKey TermsBoolean expression&& means “and”|| means “or”truth tablesparenthesesprecedence ruleshigher precedenceshort-circuitcomplete evaluationintegers convert toboolif-elsestatementparenthesesif-elsewith multiple statementscompound statementifstatementindentingmultiwayif-elseswitchstatementcontrolling expressionbreakstatementdefaultenumeration typeconditional operatorconditional operator expressionloop body iterationwhileanddo-whilecomparedexecuting the body zero timescomma operatorcomma expressionforstatementempty statementinfinite loopcontinuestatementifstreamstreamfile inputtext file

Page 24

Solution Manual for Absolute C++, 6th Edition - Page 24 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s ManualBrief Outline2.1Boolean ExpressionsBuilding Boolean ExpressionsEvaluating Boolean ExpressionsPrecedence Rules2.2Branching MechanismsIf-else StatementsCompound StatementsOmitting the elseNested StatementsMultiway if-else StatementThe switch StatementEnumeration TypesThe Conditional Operator2.3LoopsThe while and do-while statementsIncrement and Decrement Operators RevisitedThe Comma OperatorThe for statementThe break and continue statementsNested Loops2.4 Introduction to File InputReading from a Text File Using ifstream1.Introduction andTeaching SuggestionsWithout flow of control, a language is not able to make decisions. The ability to choose a paththrough code based on data is what gives a computer its power. Two flow of control issues notcovered in this chapter are function calls and exception handling. Function calls are covered inChapter 3 and exceptions in Chapter 18.This chapter discusses flow of control using both selection and iteration. The if-statement andloops are introduced both in this chapter. With both topics in one chapter, it is conceivable thatthis chapter will take longer for students to work through than many of the others in the text.Branching, or selection, is introduced using the if-else statement, the if statement, and the switchstatement. Multiple paths and therefore, nested if-else statements are introduced. As the lastform of selection available, the conditional operator is introduced at the end of the chapter.Although many students choose not to use this operator, it is useful to cover so students can readcode that does use it.With the introduction of looping and selection, students can write fairly complex programs at theend of this chapter. However, what usually begins to happen is that students will write code thathas errors. Finding these errors can be tedious and time-consuming. The sections on commonpitfalls (infinite loops, semicolon at the end of for loops, etc.) should be covered as an

Page 25

Solution Manual for Absolute C++, 6th Edition - Page 25 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s Manualintroduction to debugging.An option that would be useful to them if it is available would be tointroduce and discuss the use of your computing environment’s debugger at this time.The section on file input allows students to write programs that use real-world data.This issignificant because it allows students to move beyond toy problems.The book has severalproblems based on a list of English words. Although this section requires some “magic” codethat is not fully explained until later, students should be able to grasp the basic concepts ofreading from a text file and can begin writing program that operate on large amounts of data.2.Key PointsBoolean Expressions and Relational Operators.The Boolean operators && and || areintroduced along with ! and their use with ==, !=, <, >, <=, and >=. Truth tables and buildingcomplex Boolean expressions are important for the students to learn how to construct.Inaddition, students must also learn the precedence rules associated with these operators.If-else statement & Multiway if-else Statement.Thereare many ways to give the program asense of choice or branching. First, we can use an if-statement by itself without an else. Thisallows us the option to do something or skip over it. We can also use an if-else statement, whichallows us to take one path or another. Lastly, we can use combinations of these to have morethan two choices for execution. As the number of paths increase, so does the complexity of codefor the students. Students should be able to follow as well as write these more complicatedbranching code segments.The switch Statement.The switch also allows for branching, but it has limitations as to whatthe condition for branching can be. Also, the syntax contains more keywords and is morestructured than the if-else. Discussion of the break statement is needed here as the switch willnot function properly without the correct use of break between the cases.true and false arenumbers.True and false can be represented as the numbers 1 and 0.This issometimes used by setting a variable equal to the result of an Boolean expression, or by testing avariable inside an if-statement.Syntax for while and do-while Statements.The while and do-while loops are the indefiniteloops supported byC++. They also illustrate the differences between an entry-test and an exit-test loop.The for Statement.The for loop is a definite loop or counting loop that is also an entry-testloop. The syntax for the for loop is different from the other two loops and has a loop counterbuilt right into the construct.However, inC++, we can have more than one statement insidethe parts of the for-loop separated by commas and we can also leave parts empty, which cancreate many different results when using a for-loop.

Page 26

Solution Manual for Absolute C++, 6th Edition - Page 26 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s Manualbreak and continue.The difference between break and continue are sometimes confused bystudents, particularly scenarios where continue is useful. It can be instructive to show how thesame effect can be achieved by code using if-statements instead of break and continue.Enumeration Types.These types allow us to define a sequence of constant values that are oftenused in loops or switch statements.They map to integers.3.TipsUse switch statements for menus.The switch statement’s advantage over the if-statement isincreased clarity, especially for large numbers of items that must be compared. This makes it agood choice for implementing menus, in particular when used with functions introduced inChapter 3.Repeat-N Times Loops.A for loop is the best way to implement a count-based loop thatrepeats N times.4.PitfallsUsing = in Place of ==.The instructor should note that the very best of programmers fall intothis error. The assignmentx= 1;is an expression that has a value. The value of this expression is the value transferred to thevariable on the left-hand side of the assignment, in this case, 1.. This value could be used by aniforwhileas a condition, just as any other expression can, for example:z= (x = 1);This, in fact, is a typical C/C++ idiom. While this is used, it can be confusing. Many instructorsdiscourage its use, although some programmers do use it. Some compilers warn if an assignmentexpression is used as the Boolean expression in anifstatement or within a loop. There is away to get some further help at the cost of a little discipline. If the programmer willconsistentlywrite any constant that may appear in a comparison on the left of the==, as inif(12 == x)...;instead ofif(x == 12)...;then the compiler will catch this pitfall of using=instead of==.if(12 = x) // error:invalid l-value in assignment...;Otherwise this is very hard to see, since thislooksright.There are also difficult-to-see pitfallsin using only one&instead of&&, or one|, instead of||. Each of these is legal C++, so thestudent won’t be warned, and the program will run, and produce incorrect results. Warn them.

Page 27

Solution Manual for Absolute C++, 6th Edition - Page 27 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s ManualExtra Semicolon.If we define anenumtype, and omit the required semicolon after the endingcurly brace, the error message on some compilers is incomprehensible. On other compilers, it isas simple as “missing semicolon inenumdefinition.”The reason theenumdefinition requiresa semicolon is that one can define a variable ofenumtype between the close curly and thesemicolon.enum CompassDir {NORTH, SOUTH, EAST, WEST} direction;ThendirectionhasCompassDirtype. If the semicolon is omitted, the compiler thinks thatanything following the semicolon wants to be an identifier ofenumtype, and identifies this as anerror, and issues an error message.Another Semicolon Pitfall.This error occurs when a student adds a semicolon to the end of anif statement or for loop, e.g.:if(x == 12);x = 0;After this code segment, the variablexhas the value 0. The hard-to-see error is the semicolonat the end of the line with theif. Theifstatement expects to see a single statement after theclosing parenthesis. The semicolon produces a null statement between the close parenthesis andthe semicolon. This makes the next statement (x = 0;) out of the scope of control of theif.If theifhas anelse, as inif(x == 12);x = 0;elsex = 1;Then the error message appears at theelse. The syntax error really is the presence of theelse,rather than at the extraneous semicolon, the real perpetrator. As above, the semicolon produces anull statement between the close parenthesis and the semicolon. This makes the next statement(x=0;) out of the scope of control of theif, and makes theelseinto an “elsewithout anif” error.The text has a Pitfall section on the extra semicolon in aforloop and another that notes that theextra semicolon problem can cause an infinite loop, for example,x= 10;while(x > 0);{cout << x << endl;x--;}A program that has this loop in it will hang. As before, the extraneous semicolon after thewhilecauses the problem. Note that placing assignments in the control of anifor awhileis C (and C++ ) idiom. Even so, some compilers warn about this. To stop such runawayprograms may require killing the process or hitting control-C.5.Programming Projects Answers1. Inflation

Page 28

Solution Manual for Absolute C++, 6th Edition - Page 28 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s ManualWrite a program to estimate the future cost of an item based on the current inflation rate and thecurrent cost of the item. The inflation rate is to be entered as a percentage, e.g., 5.6 for 5.6percent. Use a loop to compute the estimated cost based on the (compounded) inflation rate.//inflation estimator//input: item cost in dollars, inflation as a percentage://for example, 5.6 for 5.6 percent, and an integral number of//years.//output: Estimate in dollars of the cost#include <iostream>using namespace std;int main(){double cost;double rate; // inflation rateint years;//years to time of requested estimatecout << "This is the Future Cost Estimator.\n"<< "Each entry is to be followed by a <return>\n\n";cout << "Enter the cost of the item in dollars:\n";cin >> cost;cout << "Enter the inflation rate as a percentage:\n"<< "such as 5.6 for 5.6 percent. ";cin >> rate;rate = rate / 100.0;cout << "Enter an integral number of years to the time\n"<< "when you want the estimate.";cin >> years;for( int i = 0; i < years; i++)cost = (1 + rate) * cost;cout << "The inflated cost is $" << cost << endl;return 0;}2. Installment Loan TimeNo 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 payoff a $1000 stereo. The following code also outputs the monthly status of the loan.#include <iostream>using namespace std;const double PAYMENT=50.00;int main(){double principal = 1000.;double interest, rate = 0.015;int months = 0;

Page 29

Solution Manual for Absolute C++, 6th Edition - Page 29 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s Manualcout << "months\tinterest\tprincipal" << endl;cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2);while(principal > 0){months++;interest = principal * rate;principal = principal-(PAYMENT-interest);if ( principal > 0 )cout << months << "\t\t" << interest << "\t\t"<< principal << endl;}cout << "number of payments = " << months;//undo the action that drove principal negative:principal = principal + (PAYMENT-interest);//include interest for last month:interest = principal * 0.015;principal = principal + interest;cout << " last months interest = " << interest;cout << " last payment = " << principal << endl;return 0;}A typical run is:monthsinterestprincipal115.00965.00214.47929.48313.94893.42413.40856.82. . .212.86143.53222.1595.68231.4447.12number of payments = 24 last months interest = 0.71 last payment = 47.833. ChocolateSuppose we can buy a chocolate bar from the vending machine for $1 each. Inside everychocolate bar is a coupon. We can redeem 7 coupons for one chocolate bar from the machine.We would like to know how many chocolate bars can be eaten, including those redeemed viacoupon, if we havendollars.For example, if we have 20 dollars then we can initially buy 20 chocolate bars. This gives us 20coupons. We can redeem 14 coupons for 2 additional chocolate bars. These two additionalchocolate bars have 2 more coupons, so we now have a total of 8 coupons when added to the sixleftover from the original purchase. This gives us enough to redeem for one final chocolate bar.As a result we now have 23 chocolate bars and 2 leftover coupons.

Page 30

Solution Manual for Absolute C++, 6th Edition - Page 30 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s ManualWrite a program that inputs the number of dollars and outputs how many chocolate bars you cancollect after spending all your money and redeeming as many coupons as possible. Also outputthe number of leftover coupons. The easiest way to solve this problem is to use a loop.CodeMate Hint: Use a while loop that redeems coupons for bars and calculates the new numberof coupons. Continue the loop as long as you have enough coupons to redeem for a chocolatebar.//chocolate.cpp////This program computes the number of candy bars we can get.//Suppose we can buy a chocolate bar from the vending machinefor $1//each.Inside every chocolate bar is a coupon.We can redeem 7//coupons for one chocolate bar from the machine.We would like to//know how many chocolate bars can be eaten, including thoseredeemed//via coupon, if we have n dollars.////This program creates a loop that simulates the process by//calculating the number of coupons we have leftover after redeeming//them for candy bars.When we don't have enough coupons toredeem,//the loop stops.#include <iostream>#include <cstdlib>using namespace std;// ======================//main function// ======================int main(){// Variable declarationsint dollars = 0;int bars = 0;int newbars = 0;int coupons = 0;cout << endl << "Enter the number of dollars you have to spend:"<< endl;cin >> dollars;////--------------------------------//-----ENTER YOUR CODE HERE-----//--------------------------------// Buy initial candy bars and number of couponsbars = dollars;coupons = bars;// Continually redeem if we have enough couponswhile (coupons >= 7)

Page 31

Solution Manual for Absolute C++, 6th Edition - Page 31 preview image

Loading page image...

Savitch, AbsoluteC++6/e: Chapter2,Instructor’s Manual{// Redeem 7 coupons for one barnewbars = coupons / 7;bars = bars + newbars;// New number of coupons is the amount leftover +// number of coupons we get from the bars we just boughtcoupons = (coupons % 7) + newbars;}// Output the number of candy bars you can getcout << "You can get " << bars << " candy bars " <<" with " << coupons << " coupons leftover."<< endl << endl;//--------------------------------//---------END USER CODE--------//--------------------------------4. PrimesWrite a program that finds and prints all of the prime numbers between 3 and 100. A primenumber is a number such that one and itself are the only numbers that evenly divide it (e.g.,3,5,7,11,13,17, …).One way to solve this problem is to use a doubly-nested loop. The outer loop can iterate from 3to 100 while the inner loop checks to see if the counter value for the outer loop is prime. Oneway to see if numbernis prime is to loop from 2 ton-1and if any of these numbers evenlydividesnthenncannot be prime. If none of the values from 2 ton-1evenly dividen, thennmust be prime. (Note that there are several easy ways to make this algorithm more efficient).//primes.cpp////This program calculates the prime numbers between 3 and 100.//It uses a doubly-nested loop.The outer loop iterates from 3 to 100//while the inner loop checks to see if the counter value forthe//outer loop is prime.To check for n to be prime, we loop from 2 to//n-1 and if any of these numbers evenly divides n then n cannot be//prime.If none of the values from 2 to n-1 evenly divide n, then n//must be prime.Note that there are several ways to make this//algorithm more efficient.#include <iostream>#include <cstdlib>using namespace std;// ======================//main function// ======================int main(){// Variable declarations
Preview Mode

This document has 689 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