Table Of ContentC++ P :
ROGRAMMING
P D I D S
ROGRAM ESIGN NCLUDING ATA TRUCTURES
F E
IFTH DITION
D.S. M
ALIK
Australia(cid:2)Brazil(cid:2)Japan(cid:2)Korea(cid:2)Mexico(cid:2)Singapore(cid:2)Spain(cid:2)UnitedKingdom(cid:2)UnitedStates
This is an electronic version of the print textbook. Due to electronic rights restrictions,
some third party content may be suppressed. Editorial review has deemed that any suppressed
content does not materially affect the overall learning experience. The publisher reserves the right
to remove content from this title at any time if subsequent rights restrictions require it. For
valuable information on pricing, previous editions, changes to current editions, and alternate
formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for
materials in your areas of interest.
C++Programming:ProgramDesign
IncludingDataStructures,FifthEdition Forproductinformationandtechnologyassistance,contactusat
CengageLearningCustomer&SalesSupport,1-800-354-9706
D.S.Malik
Forpermissiontousematerialfromthistextorproduct,submit
allrequestsonlineatwww.cengage.com/permissions
ExecutiveEditor:MarieLee
Furtherpermissionsquestionscanbeemailedto
AcquisitionsEditor:AmyJollymore
[email protected]
SeniorProductManager:AlyssaPratt
EditorialAssistant: ZinaKresin LibraryofCongressControlNumber:2010921540
ContentProjectManager:Matthew
ISBN-13:978-0-538-79809-2
Hutchinson
ISBN-10:0-538-79809-2
ArtDirector:FaithBrosnan
PrintBuyer:JulioEsperas CourseTechnology
20ChannelCenterStreet
Proofreader:GreenPenQA
Boston,MA 02210
Indexer:ElizabethCunningham USA
CoverDesigner:RoycroftDesign/
Someoftheproductnamesandcompanynamesusedinthis
www.roycroftdesign.com
bookhavebeenusedforidentificationpurposesonlyandmay
CoverPhoto:ContemporaryBuilding betrademarksorregisteredtrademarksoftheirrespective
ªSteveHix/SomosImages/Corbis manufacturersandsellers.
Compositor:Integra AnyfictionaldatarelatedtopersonsorcompaniesorURLsused
throughoutthisbookisintendedforinstructionalpurposesonly.
Atthetimethisbookwasprinted,anysuchdatawasfictional
ª2011CourseTechnology,CengageLearning andnotbelongingtoanyrealpersonsorcompanies.
ALLRIGHTSRESERVED.Nopartofthiswork CourseTechnology,apartofCengageLearning,reservesthe
coveredbythecopyrighthereinmaybe righttorevisethispublicationandmakechangesfromtimeto
reproduced,transmitted,storedorusedinany timeinitscontentwithoutnotice.
formorbyanymeansgraphic,electronic,or
Theprogramsinthisbookareforinstructionalpurposesonly.
mechanical,includingbutnotlimitedto
Theyhavebeentestedwithcare,butarenotguaranteed
photocopying,recording,scanning,digitizing,
foranyparticularintentbeyondeducationalpurposes.The
taping,Webdistribution,information
authorandthepublisherdonotofferanywarrantiesor
networks,orinformationstorageandretrieval
representations,nordotheyacceptanyliabilitieswithrespect
systems,exceptaspermittedunderSection
totheprograms.
107or108ofthe1976UnitedStatesCopyright
Act,withoutthepriorwrittenpermissionof Cengage Learning is a leading provider of customized
thepublisher. learning solutions with office locations around the globe,
including Singapore, the United Kingdom, Australia, Mexico,
Brazil and Japan. Locate your local office at:
www.cengage.com/global
Cengage Learning products are represented in Canada
by Nelson Education, Ltd.
TolearnmoreaboutCourseTechnology,visit
www.cengage.com/coursetechnology
Purchaseanyofourproductsatyourlocalcollegestoreorat
ourpreferredonlinestorewww.CengageBrain.com
TO
MyParents
Printed in the United States of America
1 2 3 4 5 6 7 16 15 14 13 12 11 10
B C
RIEF ONTENTS
PREFACE xxv
1. An Overview of Computers and Programming Languages 1
2. Basic Elements of C++ 27
3. Input/Output 117
4. Control Structures I (Selection) 175
5. Control Structures II (Repetition) 247
6. User-Defined Functions I 319
7. User-Defined Functions II 361
8. User-Defined Simple Data Types, Namespaces,
and the string Type 433
9. Arrays and Strings 485
10. Records (structs) 563
11. Classes and Data Abstraction 601
12. Inheritance and Composition 675
13. Pointers, Classes, Virtual Functions, Abstract Classes, and Lists 745
14. Overloading and Templates 827
15. Exception Handling 919
16. Recursion 959
17. Linked Lists 991
18. Stacks and Queues 1083
iv | C++Programming:ProgramDesignIncludingDataStructures,FifthEdition
19. Searching and Sorting Algorithms 1183
20. Binary Trees 1265
21. Graphs 1321
22. Standard Template Library (STL) 1361
APPENDIX A Reserved Words 1477
APPENDIX B Operator Precedence 1479
APPENDIX C Character Sets 1481
APPENDIX D Operator Overloading 1485
APPENDIX E Additional C++ Topics 1487
APPENDIX F Header Files 1509
APPENDIX G Memory Size on a System and Random
Number Generator 1519
APPENDIX H References 1521
APPENDIX I Answers to Odd-Numbered Exercises 1523
INDEX 1555
T C
ABLE OF ONTENTS
Preface xxv
AN OVERVIEW OF COMPUTERS AND PROGRAMMING
1
LANGUAGES 1
Introduction 2
A Brief Overview of the History of Computers 2
Elements of a Computer System 3
Hardware 4
CentralProcessingUnitandMainMemory 4
Input/OutputDevices 5
Software 6
The Language of a Computer 6
The Evolution of Programming Languages 8
Processing a C++ Program 10
ProgrammingwiththeProblemAnalysis–Coding–ExecutionCycle 12
Programming Methodologies 20
StructuredProgramming 20
Object-OrientedProgramming 20
ANSI/ISO Standard C++ 22
Quick Review 22
Exercises 23
BASIC ELEMENTS OF C++ 27
2
A C++ Program 28
The Basics of a C++ Program 31
Comments 32
SpecialSymbols 32
vi | C++Programming:ProgramDesignIncludingDataStructures,FifthEdition
ReservedWords(Keywords) 33
Identifiers 33
Whitespaces 34
Data Types 35
SimpleDataTypes 35
Floating-PointDataTypes 38
Arithmetic Operators and Operator Precedence 39
OrderofPrecedence 43
Expressions 44
MixedExpressions 45
Type Conversion (Casting) 47
string Type 49
Input 50
AllocatingMemorywithConstantsandVariables 50
PuttingDataintoVariables 53
AssignmentStatement 53
SavingandUsingtheValueofanExpression 56
DeclaringandInitializingVariables 57
Input(Read)Statement 58
VariableInitialization 61
Increment and Decrement Operators 65
Output 67
Preprocessor Directives 75
namespaceandUsingcinandcoutinaProgram 76
UsingthestringDataTypeinaProgram 76
Creating a C++ Program 77
Debugging: Understanding and Fixing Syntax Errors 80
Program Style and Form 84
Syntax 84
UseofBlanks 85
UseofSemicolons,Brackets,andCommas 85
Semantics 85
NamingIdentifiers 85
PromptLines 86
Documentation 87
FormandStyle 87
More on Assignment Statements 89
Programming Example: Convert Length 91
TableofContents | vii
Programming Example: Make Change 94
Quick Review 98
Exercises 100
Programming Exercises 109
INPUT/OUTPUT 117
3
I/O Streams and Standard I/O Devices 118
cinandtheExtractionOperator>> 119
Using Predefined Functions in a Program 124
cinandthegetFunction 127
cinandtheignoreFunction 128
TheputbackandpeekFunctions 130
TheDotNotationbetweenI/OStreamVariables
andI/OFunctions:APrecaution 132
Input Failure 133
TheclearFunction 135
Output and Formatting Output 137
setprecisionManipulator 137
fixedManipulator 138
showpointManipulator 139
setw 142
Additional Output Formatting Tools 144
setfillManipulator 144
leftandrightManipulators 146
Input/Output and the string Type 148
Debugging: Understanding Logic Errors
and Debugging with cout Statements 149
File Input/Output 152
Programming Example: MovieTicketsSaleandDonationtoCharity 156
Programming Example: Student Grade 162
Quick Review 165
Exercises 166
Programming Exercises 170
CONTROL STRUCTURES I (SELECTION) 175
4
Control Structures 176
Relational Operators 177
RelationalOperatorsandSimpleDataTypes 178
viii | C++Programming:ProgramDesignIncludingDataStructures,FifthEdition
ComparingCharacters 179
RelationalOperatorsandthestringType 180
Logical (Boolean) Operators and Logical Expressions 182
OrderofPrecedence 184
intDataTypeandLogical(Boolean)Expressions 187
boolDataTypeandLogical(Boolean)Expressions 188
Selection: if and if...else 188
One-WaySelection 189
Two-WaySelection 191
Compound(Blockof)Statements 195
MultipleSelections:Nestedif 195
Comparingif...elseStatementswithaSeriesofifStatements 198
Short-CircuitEvaluation 199
ComparingFloating-PointNumbersforEquality:APrecaution 200
AssociativityofRelationalOperators:APrecaution 201
AvoidingBugsbyAvoidingPartiallyUnderstood
ConceptsandTechniques 203
InputFailureandtheifStatement 206
ConfusionbetweentheEqualityOperator(==)and
theAssignmentOperator(=) 209
ConditionalOperator(?:) 211
ProgramStyleandForm(Revisited):Indentation 211
Using Pseudocode to Develop, Test, and Debug a Program 212
switch Structures 215
AvoidingBugsbyAvoidingPartiallyUnderstoodConcepts
andTechniques(Revisited) 221
Terminating a Program with the assert Function 223
Programming Example: Cable Company Billing 225
Quick Review 231
Exercises 232
Programming Exercises 241
CONTROL STRUCTURES II (REPETITION) 247
5
Why Is Repetition Needed? 248
while Looping (Repetition) Structure 249
Designing while Loops 251
Case1:Counter-ControlledwhileLoops 252
Case2:Sentinel-ControlledwhileLoops 255