Table Of ContentC++ P :
ROGRAMMING
F P A P D
ROM ROBLEM NALYSIS TO ROGRAM ESIGN
F E
OURTH 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
C++Programming:FromProblemAnalysis ª2009CourseTechnology,CengageLearning
toProgramDesign,FourthEdition
ALLRIGHTSRESERVED.Nopartofthisworkcoveredbythe
byD.S.Malik copyrighthereinmaybereproduced,transmitted,storedorused
inanyformorbyanymeansgraphic,electronic,ormechanical,
SeniorProductManager:AlyssaPratt
includingbutnotlimitedtophotocopying,recording,scanning,
AcquisitionsEditor:AmyJollymore digitizing,taping,Webdistribution,informationnetworks,or
ContentProductManager:JillBraiewa informationstorageandretrievalsystems,exceptaspermitted
MarketingManager:BryantChrzan underSection107or108ofthe1976UnitedStatesCopyrightAct,
withoutthepriorwrittenpermissionofthepublisher.
EditorialAssistant:PatrickFrank
PrintBuyer:JulioEsperas
Forproductinformationandtechnologyassistance,contactusat
CoverDesigner:LisaKuhn,CurioPress,LLC CengageLearningCustomer&SalesSupport,1-800-354-9706
Compositor:Integra Forpermissiontousematerialfromthistextorproduct,submit
allrequestsonlineatcengage.com/permissions
ArtDirector:MarissaFalco
Furtherpermissionsquestionscanbeemailedto
Validation:GreenPenQualityAssurance permissionrequest@cengage.com
Proofreader:GreenPenQualityAssurance
Indexer:LizCunningham ISBN-13:978-1-4239-0209-6
ISBN-10:1-4239-0209-2
CourseTechnology
25ThomsonPlace
Boston,MA 02210
USA
Visual(cid:2)C++.NETand PowerPoint(cid:2)areregisteredtrademarks
oftheMicrosoftCorporation;Pentium(cid:2)isaregistered
trademarkofIntelCorporation;IBMisaregisteredtrademark
ofIndustrialBusinessMachines.
Disclaimer
CourseTechnologyreservestherighttorevisethispublication
andmakechangesfromtimetotimeinitscontentwithout
notice.
Theprogramsinthisbookareforinstructionalpurposesonly.
Theyhavebeentestedwithcare,butarenotguaranteedforany
particularintentbeyondeducationalpurposes.Theauthorsand
thepublisherdonotofferanywarrantiesorrepresentations,nor
dotheyacceptanyliabilitieswithrespecttotheprograms.
Cengage Learning is a leading provider of customized
learning solutions with office locations around the globe,
including Singapore, the United Kingdom, Australia, Mexico,
Brazil, and Japan. Locate your local office at:
international.cengage.com/region
Cengage Learning products are represented in Canada
by Nelson Education, Ltd.
For your lifelong learning solutions, visit
course.cengage.com
Visit our corporate website at cengage.com
Printed in Canada
1 2 3 4 5 6 7 14 13 12 11 10 09 08
TO
My Daughter
Shelly Malik
B C
RIEF ONTENTS
PREFACE xxvii
1. An Overview of Computers and Programming Languages 1
2. Basic Elements of C++ 29
3. Input/Output 115
4. Control Structures I (Selection) 167
5. Control Structures II (Repetition) 231
6. User-Defined Functions I 307
7. User-Defined Functions II 345
8. User-Defined Simple Data Types, Namespaces,
and the string Type 415
9. Arrays and Strings 469
10. Applications of Arrays (Searching and Sorting)
and the vector Type 545
11. Records (structs) 603
12. Classes and Data Abstraction 641
13. Inheritance and Composition 717
14. Pointers, Classes, Virtual Functions, and Abstract Classes 785
15. Overloading and Templates 853
16. Exception Handling 943
17. Recursion 981
18. Linked Lists 1017
19. Stacks and Queues 1111
vi | C++Programming:FromProblemAnalysistoProgramDesign,FourthEdition
APPENDIX A Reserved Words 1219
APPENDIX B Operator Precedence 1221
APPENDIX C Character Sets 1223
APPENDIX D Operator Overloading 1227
APPENDIX E Additional C++ Topics 1229
APPENDIX F Header Files 1251
APPENDIX G Memory Size on a System and Random
Number Generator 1261
APPENDIX H Standard Template Library (STL) 1263
APPENDIX I Answers to Odd-Numbered Exercises 1305
INDEX 1327
T C
ABLE OF ONTENTS
Preface xxvii
AN OVERVIEW OF COMPUTERS
1
AND PROGRAMMING LANGUAGES 1
Introduction 2
A Brief Overview of the History of Computers 2
Elements of a Computer System 3
Hardware 4
Central Processing Unit 4
Main Memory 5
Secondary Storage 6
Input/Output Devices 6
Software 6
The Language of a Computer 6
The Evolution of Programming Languages 8
A C++ Program 10
Processing a C++ Program 12
Programming with the Problem
Analysis–Coding–Execution Cycle 14
Programming Methodologies 22
Structured Programming 22
Object-Oriented Programming 22
ANSI/ISO Standard C++ 24
Quick Review 24
Exercises 26
viii | C++Programming:FromProblemAnalysistoProgramDesign,FourthEdition
BASIC ELEMENTS OF C++ 29
2
The Basics of a C++ Program 30
Comments 32
Special Symbols 32
Reserved Words (Keywords) 33
Identifiers 33
Whitespaces 34
Data Types 34
Simple Data Types 35
Floating-Point Data Types 38
Arithmetic Operators and Operator Precedence 40
Order of Precedence 44
Expressions 45
Mixed Expressions 46
Type Conversion (Casting) 48
string Type 50
Input 51
Allocating Memory with Constants and Variables 52
Putting Data into Variables 54
Assignment Statement 54
Saving and Using the Value of an Expression 58
Declaring and Initializing Variables 59
Input (Read) Statement 60
Variable Initialization 63
Increment and Decrement Operators 67
Output 69
Preprocessor Directives 77
namespace and Using cin and cout in a Program 78
Using the string Data Type in a Program 78
Creating a C++ Program 79
Program Style and Form 83
Syntax 83
Use of Blanks 84
TableofContents | ix
Use of Semicolons, Brackets, and Commas 84
Semantics 84
Naming Identifiers 84
Prompt Lines 85
Documentation 86
Form and Style 86
More on Assignment Statements 88
Programming Example: Convert Length 99
Programming Example: Make Change 93
Quick Review 97
Exercises 99
Programming Exercises 107
INPUT/OUTPUT 115
3
I/O Streams and Standard I/O Devices 116
cin and the Extraction Operator >> 117
Using Predefined Functions in a Program 123
cin and the get Function 125
cin and the ignore Function 126
The putback and peek Functions 128
The Dot Notation Between I/O Stream Variables
and I/O Functions: A Precaution 130
Input Failure 131
The clear Function 133
Output and Formatting Output 135
setprecision Manipulator 135
fixed Manipulator 136
showpoint Manipulator 136
setw 138
Additional Output Formatting Tools 141
setfill Manipulator 141
left and right Manipulators 143
Input/Output and the string Type 145
x | C++Programming:FromProblemAnalysistoProgramDesign,FourthEdition
File Input/Output 146
Programming Example: Movie Ticket Sale and
Donation to Charity 150
Programming Example: Student Grade 155
Quick Review 158
Exercises 160
Programming Exercises 163
CONTROL STRUCTURES I (SELECTION) 167
4
Control Structures 168
Relational Operators 169
Relational Operators and Simple Data Types 171
Comparing Floating-point Numbers for equality 171
Comparing Characters 172
Relational Operators and the string Type 173
Logical (Boolean) Operators and Logical Expressions 175
Order of Precedence 177
Short-Circuit Evaluation 181
int Data Type and Logical (Boolean) Expressions 182
bool Data Type and Logical (Boolean) Expressions 183
Selection: if and if...else 184
One-Way Selection 185
Two-Way Selection 187
Compound (Block of) Statements 191
Multiple Selections: Nested if 192
Comparing if...else Statements with
a Series of if Statements 196
UsingPseudocodetoDevelop,Test,andDebugaProgram 196
Input Failure and the if Statement 199
Confusion Between the Equality Operator (==) and
the Assignment Operator (=) 202
Conditional Operator (?:) 203
switch Structures 204