instructor’s resource manualwps.aw.com/wps/media/objects/80/82902/savitchimch01.doc · web...
TRANSCRIPT
INSTRUCTOR’S RESOURCE MANUALTO ACCOMPANY
Absolute C++Walter Savitch
UNIVERSITY OF CALIFORNIA, SAN DIEGOInstructor's Resource Manual developed by David Teague, Western Carolina. University
Addison-Wesley Publishing Company
Boston San Francisco New York London
Toronto Sydney Tokyo Singapore Madrid Mexico City
Munich Paris Cape Town Hong Kong Montreal
To keep current with this product, please visit the web site for this book,
http://www.aw.com/savitch and please visit our computer science web site at:
http://www.aw.com/cs/
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 2
Chapter 1 C++ Basics
Copyright © 2002 by Pearson Education, Inc.
All right reserved. No part of this publication may be reproduced, stored in a retrieval system, or
transmitted, in any form or by any means, electronic, mechanical, photo-copying, recording, or any other
media embodiments now known or hereafter to become known, without the prior written permission of the
publisher. Printed in the United States of America.
Permission is given for any use for instructional purposes by any teacher who has adopted the text.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where these designations appear in this book, and the publisher was aware of a trademark
claim, the designations have been printed in initial caps or all caps.
The programs and the applications presented in this book have been included for their instructional value.
They have been tested with care but are not guaranteed for any particular purpose. Neither the publisher
nor the author offers any warranties or representations, nor do they severally or individually accept any
liabilities with respect to the programs or applications.
Addison-Wesley Publishing Company
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 3
Chapter 1 C++ Basics
Contents of the Text
Preface
Chapter 1 Introduction to C++
Chapter 2 Flow of Control
Chapter 3 Function Basics
Chapter 4 Parameters and Overloading
Chapter 5 Arrays
Chapter 6 Structures and Classes
Chapter 7 Constructors and Other Tools
Chapter 8 Operator Overloading, Friends, and References
Chapter 9 Strings
Chapter 10 Pointers and Dynamic Arrays
Chapter 11 Separate Compilation and Namespaces
Chapter 12 Stream and File I/O
Chapter 13 Recursion
Chapter 14 Inheritance
Chapter 15 Polymorphism and Virtual Functions
Chapter 16 Templates
Chapter 17 Linked Data Structure
Chapter 18 Exception Handling
Chapter 19 Standard Template Library
Chapter 20 Patterns and UML
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 4
Chapter 1 C++ Basics
PrefaceThis 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. There is a
Test Bank in the form of an electronic supplement the consists of 40 to 50 test questions
with answers and discussion for each chapter. The questions are of both short answer
(multiple choice, true false, fill in the blank) type as well as discussion , 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 than the author. 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.
I have usually compiled the code using a PC running Debian Linux 3.0 (Woody) using
egcs C++ compiler (g++3.0). In a most situations I have also compiled the code with
Borland's 5.5 Command line compiler and Visual C++ 6.0 patch level 5, running on the
same machine under Windows 2000. With some variation, each of these compilers follows
the 1996 ISO/ANSI C++ Standard.
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 5
Chapter 1 C++ Basics
There are many unpatched copies of VC++ 6.0 in use. Urge the student using this compiler
to download and apply patches to bring their compiler to patch level 5. Patching is easy
and results in the code from the book and this IRM compiling with far fewer bugs.
I have used only mainstream features of C++; consequently, most compilers will produce
output that does not differ significantly from the results presented here. Where I find
variances, I will try to point these out.
Thanks go to Walt Savitch, for writing the book for which this is a supplement and for
reading the IRM and Test Bank. He made many valuable comments that invariably
improved it. Thanks go to Galia Shoky, Editorial Assistant for assistance and resources; to
Emily Genaway, Acquisitions Editor, for encouragement and a schedule that kept me
working hard, yet was possible to manage; and to Susan Hartman Sullivan, Publisher, for
the opportunity to continue to contribute to my profession in retirement.
Finally, I want to thank my wife, Judy, who tolerated my absence when I should have
spent the time with her.
In spite of careful reading by Walt Savitch and others, any errors that may remain here are
mine and mine alone.
David Teague
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 6
Chapter 1 C++ Basics
Instructor's Resource Manualfor
Savitch, Absolute C++
This document is intended to be a resource guide for instructors using Savitch, Absolute
C++. This guide follows the text chapter by chapter. Each chapter of this guide contains
the following sections:
1. Outline of topics in the chapter
2. General remarks on the chapter
3. Solutions to, and remarks on, selected Programming Projects
Introduction:
Our book is designed to be both a text and a reference for programming in the C++
language. While it contains programming techniques, it is organized around language
concepts rather than curricular ideas. The book is intended for undergraduates who have
not had extensive programming experience with the C++ language. As such, it would be a
suitable text for a second CS course with C++ as the language.
The beginning chapters are written at a level accessible to beginners, but the ideas are
displayed in boxed sections in a way that more advanced students can quickly pick up the
ideas and proceed at a faster pace. The later chapters are at a higher level.
For those who need additional pedagogical material, the author has written another text.
The book is: Walter Savitch, Problem Solving with C++: The Object of Programming,
Third Edition, Addison Wesley Publishing Co. © 2001, ISBN 0-201-70390-4. The book is
shipped with an introductory version of VC++6.0.
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 7
Chapter 1 C++ Basics
Chapter 1Introduction to C++
1. Outline of topics in the chapter1.1 Introduction to C++
1.2 Variables, Expressions, and Assignment Statements
1.3 Console Input/Output
1.4 Program Style
1.5 Libraries and Namespaces
2. General remarks on the chapterThis chapter introduces the C++ language in enough detail to code the solution to simple
programs that use expression evaluation, assignments, and console i/o. C++ expressions
and assignments are identical to those in C and are similar to other high-level languages.
Each language has its own console i/o, and C++ is no exception.
Encourage the student to learn the terminology. This 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 will better understand the text, will be better prepared for further work, and will have far less trouble with this course.
Students should be given an indication of the amount of work that must be done before
coding. Planning should be required from the start. There are instances where several man-
years of work have gone into software before a single line of code was written.
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 8
Chapter 1 C++ Basics
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 desk checked.
Emphasize that the program design process is 'iterative'. 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, and
OUTPUT phases, though frequently these will need to be integrated. (In Chapter 20 they
will see this as the Model-View-Controller pattern.) 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.
Emphasize the importance of readability of code by other programmers. Meaningful
names contribute to readability. Where one puts curly braces (a generator of much heat,
but not much light) or whether spaces set off operators is important. However, consistency
of style is the single most important item in a very long list of contributors to code
readability.
The student should strive for code that is self-documenting. The use of identifier names
that have meaning within the context of the problems being solved goes a long way in this
direction.
Code that is not self documenting for whatever reasons may be made clearer by appropri-
ate (minimal) comments inserted in the code.
"The most difficult feature of any programming language to master is the
comment."
-- a disgruntled maintenance programmer.
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 9
Chapter 1 C++ Basics
"Where the comment and the code disagree, both should be assumed to be in
error."
-- an experienced maintenance programmer.
Remarks can clarify difficult points, but if the comment doesn't add to what can be gleaned
from the program code itself, the comment is unnecessary, indeed it gets in the way. Good
identifier names can reduce the necessity for comments!
With these cautions in mind, the student should place remarks at the top of file containing
program components, describing the purpose. Exactly what output is required should be
specified, and any conditions on the input to guarantee correct execution should be
specified.
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 & Borland's C++ the error message is likely be something about an "illegal structure
operation in function (whatever):". 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.
You will have the occasional student who has significant C programming experience.
These students will insist on using the C style standard i/o library declared in <stdio.h>
input-output. (This is available in C++ as cstdio, with namespace issues.) Discourage
this, and insist on C++ iostream i/o. This is because the iostream library understands
and uses the C++ type system You have to tell stdio i/o functions every type for every
output you attempt. If you don't get it right, then an error in the output may not be obvi-
ous. Either iostream knows the type, or the linker will complain that it doesn't have the
member functions to handle the type you are using. Further, it is possible to do almost all
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 10
Chapter 1 C++ Basics
i/o using the stream operators >> and << : file i/o, device i/o, as well as console
i/o. You can overload the operator>> and operator<< functions to carry out i/o
for any and all objects you define. You can also adjust behavior of stream i/o to your taste
using manipulators.
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 in the details that are
checked.. The Borland compilers are sufficiently demanding by default.
The GNU C++ compiler, g++-3.0, Microsoft’s Visual C++ 6.0 (if at patch-level 5), and
the Borland compiler version 5 and later very nearly meet the new C++ Standard. Each of
these compilers and the associated libraries closely conform to the standard. Each has
discrepancies that I will mention as code is presented. However, the libraries distributed
with the earlier g++-2.9.5 version of GNU C++ do not do not put names from header files
that do not have the .h extension into namespace std as required by the C ++
Standard. More will be said of this later. Each of these compilers provides for adjustment
with respect to the kinds of errors and warnings that are issued. Read the help for Borland
and VC++ . There is not a lot of documentation for g++. There is a Linux man page for g+
+ that, while written circa 1993, is still reasonably current. For gcc/g++ versions 2.9.5 and
later, the distribution contains a gcc/g++ manual in postscript format. The manuals are
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 11
Chapter 1 C++ Basics
available on the web at gcc.gnu.org/onlinedocs/. More libraries are available at
www.boost.org.
The student should be strongly encouraged to create examples and to ask compiler about
the C++ language that the particular compiler accepts. The compiler is the final authority
on the version of the language that it accepts, regardless of what the C++ standard might
say.
How Do I Find What Key Will Stop My Program?Some code must be killed to get back control of the computer. Under UNIX, Linux or
other Unix work-alike systems, several system-defined keys will terminate a program. The
one named kill is the best one to try first. This is usually control-c, but under
System V, this may be the delete key. If this fails, the current value for a Unix or Linux
system may be found by typing the command stty at the system prompt. The command
stty -a may be necessary. (The space between stty and the - is required. There
must be no space between the - and the a. In this last case, you may wish to type stty
-a | more (this is stty -a, piped into more) to get this information a screenful at a
time. This gives you more information than you ever wanted about the terminal settings.
The values of interest are intr, quit and kill. These are set to ^C, ^\, and (^U
control C, control-back-slash and control U) on this writer's Linux
system.
Under Windows 9x (including Me), if a program stops responding, then pressing
control-alt-del once (simultaneously press the three keys) will bring up a menu of
processes, providing you with the opportunity to kill the offending program. Note that
pressing control-alt-del twice will reboot the computer, killing everything.
If all else fails, pressing the reset button, or cycling the power is the only option, but you
risk damaging a file system if you find that necessary.
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 12
Chapter 1 C++ Basics
3. Solutions and remarks on selected Programming Projects
1. Metric - English units ConversionA 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:
The explicit 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.
Let metricTonsPerBox be the weight of the cereal contained in the box in metric tons,
and let ouncesPerBox be the weight of the cereal contained in the box in ounces. Then
in C++ the formula becomes:
const double ouncesPerMetricTon = 35272.92;
metricTonsPerBox = ouncesPerBox/ouncesPerMetricTon;
This is metric tons PER BOX, whence the number of BOX(es) PER metric ton should be the reciprocal of this number: boxesPerMetricTon = 1 / metricTonsPerBox;
Once this analysis is made, the code proceeds quickly:
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 13
Chapter 1 C++ Basics
// 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>
using namespace std;
const double oncesPerMetricTon = 35272.92;
int main(){
double ouncesPerBox, 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;
return 0;}
A sample run follows:~/AW$ a.out
enter the weight in ounces of your favorite cereal:
14
metric tons per box = 0.000396905
boxes to yield a metric ton = 2519.49
enter the weight in ounces of your favorite cereal:
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 14
Chapter 1 C++ Basics
2. Lethal DoseI have reworded this problem slightly.
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 some more or less
reasonable assumption as basis for the calculation.
This solution supposes the lethal dose is directly proportional to the weight of the subject,
hence
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 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, or will not care. 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 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 = lethalDoseForDieter / (0.35 grams / can)
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 15
Chapter 1 C++ Basics
//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 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>
using namespace std;
const double concentration = .001; // 1/10 of 1 percent
const double canWeight = 350;
const double gramsSweetenerPerCan =
canWeight * concentration; //units: grams/can
int main(){
double lethalDoseMouse, lethalDoseDieter, weightMouse, weightDieter; //units: grams
double cans;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 weightDieter/weightMouse;
cout << "For these parameters:\nmouse weight: "
<< weightMouse
<< " grams " << endl
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 16
Chapter 1 C++ Basics
<< "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;
return 0;}
A typical run follows:
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
3. Pay IncreaseThe workers have won a 7.6% pay increase, effective 6 months retroactively. This
program is to accept the previous 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:
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 17
Chapter 1 C++ Basics
newSalary = salary * ( 1 + INCREASE );
monthly = salary / 12;
retroactive = (newSalary – salary) / 2;
The code follows:
//Given 6 months retroactive, 7.6% pay increase,
//Input: old salary
//Output: new annual and monthly salary, retroactive pay due
#include <iostream>
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;
salary = oldSalary * ( 1 + INCREASE );
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.
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 18
Chapter 1 C++ Basics
100000
I'll return new annual salary, monthly salary, and retroactive
pay.
new annual salary 107600
new monthly salary 8966.67
retroactive salary due: 53800
4. Consumer LoanThis problem is of interest to me because it is an example where the student needs to have
a solution in hand before going to the 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:
InterestRate and NoYearsToRun:
AmountRecevied = FaceValue – discount
Discount = FaceValue * AnnualInterestRate * NoYearsToRun;
AmountReceived =
FaceValue – FaceValue*AnnualInterestRate*NoYearsToRun
Then ask them to solve for FaceValue:
FaceValue = AmountReceived / (1 -
AnnualInterestRate*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
maximum has been exceeded, announces either that the room has its maximum occupancy
exceeded and how many must leave, else it announces that the maximum has not been ex-
ceeded.
This problem uses the if-else illustrated in Display 1.1, and a one-sided if statement,
//Maximum Occupancy
#include <iostream>
using namespace std;
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 19
Chapter 1 C++ Basics
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";
else
cout <<"The number of occupants does not exceed "
<< "the legal maximum.\n";
return 0;
}
/*
A typical run is:
Enter the Maximum occupancy for the room.
250
Enter the number of occupants of the room.
375
ATTENTION: MAXIMUM OCCUPANCY EXCEEDED.
THE LAW REQUIRES 125 PERSONS TO LEAVE THE ROOM IMMEDIATELY
Another run:
Enter the Maximum occupancy for the room.
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 20
Chapter 1 C++ Basics
250
Enter the number of occupants of the room.
225
The number of occupants does not exceed the legal maximum.
*/
6. Overtime Pay This problem uses the if-else illustrated in Display 1.1, and a one-sided if statement,
which is just an if-else with the else clause 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;
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 21
Chapter 1 C++ Basics
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 cents
cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout.precision(2);
// compute payroll
cout << "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 )
grossPay = hoursWorked * PAYRATE;
else
overTime =
(hoursWorked - 40) * PAYRATE * OVERTIME_FACTOR;
if (hoursWorked > 40)
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 22
Chapter 1 C++ Basics
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;
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 23
Chapter 1 C++ Basics
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)
234567890
234567890
Please enter hours worked
37.00
37.00
Please enter number of dependants.
1
1
Employee number: 234567890
hours worked: 37.00
regular pay rate: 16.78
gross pay: 620.86
FICA tax withheld: 37.25
Federal Income Tax withheld: 86.92
State Tax withheld: 31.04
Flabbergaster's Union Dues withheld: 10.00
Net Pay: 455.64
Enter employee SSN (digits only, no spaces or dashes)
234567890
234567890
Please enter hours worked
Instructor’s Resource Manual for Savitch Absolute C++ 05/06/23 Page 24
Chapter 1 C++ Basics
54.00
54.00
Please enter number of dependants.
4
4
Employee number: 234567890
hours worked: 54.00
regular pay rate: 16.78
overtime hours worked: 14.00
with overtime premium: 1.50
gross pay: 1023.58
FICA tax withheld: 61.41
Federal Income Tax withheld: 143.30
State Tax withheld: 51.18
Health Insurance Premium withheld: 35.00
Flabbergaster's Union Dues withheld: 10.00
Net Pay: 722.69
/*