C++ P : ROGRAMMING F P A P D ROM ROBLEM NALYSIS TO ROGRAM ESIGN F E IFTH DITION D.S. M ALIK Australia(cid:1)Brazil(cid:1)Japan(cid:1)Korea(cid:1)Mexico(cid:1)Singapore(cid:1)Spain(cid:1)UnitedKingdom(cid:1)UnitedStates C++Programming:FromProblemAnalysis toProgramDesign,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:2009942948 ContentProjectManager:Matthew ISBN-13:978-0-538-79808-2 Hutchinson ISBN-10:0-538-79808-4 ArtDirector:FaithBrosnan PrintBuyer:JulioEsperas CourseTechnology 20ChannelCenterStreet CoverDesigner:RoycroftDesign/ Boston,MA 02210 www.roycroftdesign.com USA CoverPhoto:ªGuntmarFritz/Masterfile Someoftheproductnamesandcompanynamesusedinthis Proofreader:GreenPenQA bookhavebeenusedforidentificationpurposesonlyandmay Indexer:ElizabethCunningham betrademarksorregisteredtrademarksoftheirrespective Compositor:Integra manufacturersandsellers. AnyfictionaldatarelatedtopersonsorcompaniesorURLsused throughoutthisbookisintendedforinstructionalpurposesonly. ª2011CourseTechnology,CengageLearning Atthetimethisbookwasprinted,anysuchdatawasfictional andnotbelongingtoanyrealpersonsorcompanies. ALLRIGHTSRESERVED.Nopartofthiswork coveredbythecopyrighthereinmaybe CourseTechnology,apartofCengageLearning,reservesthe reproduced,transmitted,storedorusedinany righttorevisethispublicationandmakechangesfromtimeto formorbyanymeansgraphic,electronic,or timeinitscontentwithoutnotice. mechanical,includingbutnotlimitedto Theprogramsinthisbookareforinstructionalpurposesonly. photocopying,recording,scanning,digitizing, Theyhavebeentestedwithcare,butarenotguaranteed taping,Webdistribution,information foranyparticularintentbeyondeducationalpurposes.The networks,orinformationstorageandretrieval authorandthepublisherdonotofferanywarrantiesor systems,exceptaspermittedunderSection representations,nordotheyacceptanyliabilitieswithrespect 107or108ofthe1976UnitedStatesCopyright totheprograms. Act,withoutthepriorwrittenpermissionof thepublisher. 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: 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 Printed in the United States of America 1 2 3 4 5 6 7 16 15 14 13 12 11 10 TO My Daughter Shelly Malik This page intentionally left blank B C RIEF ONTENTS 1. AnOverviewofComputersandProgrammingLanguages1 2. BasicElementsofC++27 3. Input/Output117 4. ControlStructuresI(Selection)175 5. ControlStructuresII(Repetition)247 6. User-DefinedFunctionsI319 7. User-DefinedFunctionsII361 8. User-DefinedSimpleDataTypes,Namespaces, andthe string Type433 9. ArraysandStrings485 10. ApplicationsofArrays(SearchingandSorting) andthe vector Type563 11. Records( structs)611 12. ClassesandDataAbstraction649 13. InheritanceandComposition723 14. Pointers,Classes,VirtualFunctions,andAbstractClasses793 15. OverloadingandTemplates861 16. ExceptionHandling951 17. Recursion991 vi | C++Programming:FromProblemAnalysistoProgramDesign,FifthEdition 18. Linked Lists 1023 19. Stacks and Queues 1115 APPENDIX A Reserved Words 1215 APPENDIX B Operator Precedence 1217 APPENDIX C Character Sets 1219 APPENDIX D Operator Overloading 1223 APPENDIX E Additional C++ Topics 1225 APPENDIX F Header Files 1247 APPENDIX G Memory Size on a System and Random Number Generator 1257 APPENDIX H Standard Template Library (STL) 1259 APPENDIX I Answers to Odd-Numbered Exercises 1301 INDEX 1331 T C ABLE OF ONTENTS Preface xxvii 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 Central Processing Unit and Main Memory 4 Input/Output Devices 5 Software 6 The Language of a Computer 6 The Evolution of Programming Languages 8 Processing a C++ Program 10 Programming with the Problem Analysis–Coding–Execution Cycle 12 Programming Methodologies 20 Structured Programming 20 Object-Oriented Programming 20 ANSI/ISO Standard C++ 22 Quick Review 22 Exercises 23 viii | C++Programming:FromProblemAnalysistoProgramDesign,FifthEdition BASIC ELEMENTS OF C++ 27 2 A C++ Program 28 The Basics of a C++ Program 31 Comments 32 Special Symbols 32 Reserved Words (Keywords) 33 Identifiers 33 Whitespaces 34 Data Types 35 Simple Data Types 35 Floating-Point Data Types 38 Arithmetic Operators and Operator Precedence 39 Order of Precedence 43 Expressions 44 Mixed Expressions 45 Type Conversion (Casting) 47 string Type 49 Input 50 Allocating Memory with Constants and Variables 50 Putting Data into Variables 53 Assignment Statement 53 Saving and Using the Value of an Expression 56 Declaring and Initializing Variables 57 Input (Read) Statement 58 Variable Initialization 61 Increment and Decrement Operators 65 Output 67 Preprocessor Directives 75 namespace and Using cin and cout in a Program 76 Using the string Data Type in a Program 76 Creating a C++ Program 77 Debugging: Understanding and Fixing Syntax Errors 80 TableofContents | ix Program Style and Form 84 Syntax 84 Use of Blanks 85 Use of Semicolons, Brackets, and Commas 85 Semantics 85 Naming Identifiers 85 Prompt Lines 86 Documentation 87 Form and Style 87 More on Assignment Statements 89 Programming Example: Convert Length 91 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 cin and the Extraction Operator >> 119 Using Predefined Functions in a Program 124 cin and the get Function 127 cin and the ignore Function 128 The putback and peek Functions 130 The Dot Notation between I/O Stream Variables and I/O Functions: A Precaution 132 Input Failure 133 The clear Function 135 Output and Formatting Output 137 setprecision Manipulator 137 fixed Manipulator 138 showpoint Manipulator 139 setw 142