Starting Out with C++: Early Objects [9 ed.] 0134400240, 9780134400242

For courses in C++ Programming. Fundamentals of C++ for Novices and Experienced Programmers Alike Intended for use in

341 83 155MB

English Pages 1272 [1275] Year 2016

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Front Cover
Title Page
Copyright Page
Contents at a Glance
CONTENTS
Preface
About the Authors
1. Introduction to Computers and Programming
1.1 Why Program
1.2 Computer Systems: Hardware and Software
1.3 Programs and Programming Languages
1.4 What Is a Program Made Of?
1.5 Input, Processing, and Output
1.6 The Programming Process
1.7 Tying It All Together: Hi! It's Me
Review Questions and Exercises
Programming Challenges
2. Introduction to C++
2.1 The Parts of a C++ Program
2.2 The count Object
2.3 The #include Directive
2.4 Variables and the Assignment Statement
2.5 Literals
2.6 Identifiers
2.7 Integer Data Types
2.8 Floating-Point Data Tyes
2.9 The char Data Type
2.10 The C++ string Class
2.11 The bool Data Type
2.12 Determining the Size of a Data Type
2.13 More on Variable Assignments and Initialization
2.14 Scope
2.15 Arithmetic Operators
2.16 Comments
2.17 Programming Style
2.18 Tying It All Together: Smile!
Review Questions and Exercises
Programming Challenges
3. Expressions and Interactivity
3.1 The cin object
3.2 Mathematical Expressions
3.3 Data Types Conversion and Type Casting
3.4 Overflow and Underflow
3.5 Named Constants
3.6 Multiple and Combined Assignment
3.7 Formatting Output
3.8 Working with Characters and Strings
3.9 More Mathematical Library Functions
3.10 Random Numbers
3.11 Focus on Debugging: Hand Tracing a Program
3.12 Green Fields Landscaping Case Study-Part 1
3.13 Tying It All Together: Word Game
Review Questions and Exercises
Programming Challenges
4. Making Decisions
4.1 Relational Operators
4.2 The if Statement
4.3 The if/else Statement
4.4 The if/else if Statement
4.5 Menu-Driven Programs
4.6 Nested if Statements
4.7 Logical Operators
4.8 Validating User Input
4.9 More about Blocks and Scope
4.10 More about Characters and Strings
4.11 The Conditional Operator
4.12 The switch Statement
4.13 Enumerated Data Types
4.14 Focus on Testing and Debugging: Validating Output Results
4.15 Green Fields Landscaping Case Study-Part 2
4.16 Tying It All Together: Fortune Teller
Review Questions and Exercises
Programming Challenges
5. Looping
5.1 Introduction to Loops: The while Loop
5.2 Using the while Loop for Input Validation
5.3 The Increment and Decrement Operators
5.4 Counters
5.5 Keeping a Running Total
5.6 Sentinels
5.7 The do-while Loop
5.8 The for Loop
5.9 Focus on Software Engineering: Deciding Which Loop to Use
5.10 Nested Loops
5.11 Breaking Out of a Loop
5.12 Using Files for Data Storage
5.13 Focus on Testing and Debugging: Creating Good Test Data
5.14 Central Mountain Credit Union Case Study
5.15 Tying It All Together: What a Colorful World
Review Questions and Exercises
Programming Challenges
6. Functions
6.1 Modular Programming
6.2 Defining and Calling Functions
6.3 Function Prototypes
6.4 Sending Data into a Function
6.5 Passing Data by Value
6.6 The return Statement
6.7 Returning a Value from a Function
6.8 Returning a Boolean Value
6.9 Using Functions in a Menu-Driven Program
6.10 Local and Global Variables
6.11 Static Local Values
6.12 Default Arguments
6.13 Using Reference Variables as Parameters
6.14 Overloading Functions
6.15 The exit() Function
6.16 Stubs and Drivers
6.17 Little Lotto Case Study
6.18 Tying It All Together: Glowing Jack-o-lantern
Review Questions and Exercises
Programming Challenges
7. Introduction to Classes and Objects
7.1 Abstract Data Types
7.2 Object-Oriented Programming
7.3 Introduction to Classes
7.4 Creating and Using Objects
7.5 Defining Member Functions
7.6 Constructors
7.7 Destructors
7.8 Private Member Functions
7.9 Passing Objects to Functions
7.10 Object Composition
7.11 Focus on Software Engineering: Seperating Class Specification, Implementation, and Client Code
7.12 Structures
7.13 More about Enumerated Data Types
7.14 Home Software Company OOP Case Study
7.15 Introduction to Object-Oriented Analysis and Design
7.16 Screen Control
7.17 Tying It All Together: Yoyo Animation
Review Questions and Exercises
Programming Challenges
8. Arrays
8.1 Arrays Hold Multiple Values
8.2 Accessing Array Elements
8.3 Inputting and Displaying Array Data
8.4 Array Initialization
8.5 The Range-Based for Loop
8.6 Processing Array Contents
8.7 Using Parallel Arrays
8.8 The typedef Statement
8.9 Arrays Function Arguments
8.10 Two-Dimensional Arrays
8.11 Arrays with Three or More Dimensions
8.12 Vectors
8.13 Arrays of Objects
8.14 National Commerce Bank Case Study
8.15 Tying It All Together: Rock, Paper, Scissors
Review Questions and Exercises
Programming Challenges
9. Searching, Sorting, and Algorithm Analysis
9.1 Introduction to Search Algorithms
9.2 Searching an Array of Objects
9.3 Introduction to Sorting Algorithms
9.4 Sorting an Array of Objects
9.5 Sorting and Searching Vectors
9.6 Introduction to Analysis of Algorithms
9.7 Case Studies
9.8 Tying It All Together: Secret Messages
Review Questions and Exercises
Programming Challenges
10. Pointers and the Address Oerator
10.1 Pointers and the Address Operator
10.2 Pointer Variables
10.3 The Relationship Between Arrays and Pointers
10.4 Pointer Arithmetic
10.5 Initializing Pointers
10.6 Comparing Pointers
10.7 Pointers as Function Parameters
10.8 Pointers to Constants and Constant Pointers
10.9 Focus on Software Engineering: Dynamic Memory Allocation
10.10 Focus on Software Engineering: Returning Pointers from Functions
10.11 Pointers to Class Objects and Structures
10.12 Focus on Software Engineering: Selecting Members of Objects
10.13 Smart Pointers
10.14 Tying It All Together: Pardon Me, Do You Have the Time?
Review Questions and Exercises
Programming Challenges
11. More about Classes and Object-Oriented Programming
11.1 The this Pointer and Constant Member Functions
11.2 Static Members
11.3 Friends of Classes
11.4 Memberwise Assignment
11.5 Copy Constructors
11.6 Operator Overloading
11.7 Rvalue References and Move Operations
11.8 Function Objects and Lambda Expressions
11.9 Type Conversion Operators
11.10 Convert Constructors
11.11 Aggregation and Composition
11.12 Inheritance
11.13 Protected Members and Class Access
11.14 Constructors, Destructors, and Inheritance
11.15 Overriding Base Class Functions
11.16 Tying It All Together: Putting Data on the World Wide Web
Review Questions and Exercises
Programming Challenges
12. More on C-Strings and the string Class
12.1 C-Strings
12.2 Library Functions for Working with C-Strings
12.3 Converstions Between Numbers and Strings
12.4 Writng Your Own C-String Handling Functions
12.5 More about the C++ string Class
12.6 Advanced Software Enterprises Case Study
12.7 Tying It All Together: Program Execution Environments
Review Questions and Exercises
Programming Challenges
13. Advanced File and I/O Operations
13.1 Input and Output Streams
13.2 More Detailed Error Testing
13.3 Member Functions for Reading and Writing Files
13.4 Binary Files
13.5 Creating Records with Structures
13.6 Random-Access Files
13.7 Opening a File for Both Input and Output
13.8 Online Friendship Connections Case Study: Object Serialization
13.9 Tying It All Together: File Merging and Color-Coded HTML
Review Questions and Exercises
Programming Challenges
14. Recursion
14.1 Introduction to Recursion
14.2 The Recursive Factorial Function
14.3 The Recursive gcd Function
14.4 Solving Recursively Defined Problems
14.5 A Recursive Binary Search Function
14.6 Focus on Problem Solving and Program Design: The QuickSort Algorithm
14.7 The Towers of Hanoi
14.8 Focus on Problem Solving: Exhaustive and Enumeration Algorithms
14.9 Focus on Software Engineering: Recursion versus Iteration
14.10 Tying It All Together: Infix and Prefix Expressions
Review Questions and Exercises
Programming Challenges
15. Polymorphism and Virtual Functions
15.1 Type Compatibility in Inheritance Hierarchies
15.2 Polymorphism and Virtual Member Functions
15.3 Abstract Base Classes and Pure Virtual Functions
15.4 Focus on Object-Oriented Programming: Composition versus Inheritance
15.5 Secure Encryption Systems, Inc., Case Study
15.6 Tying It All Together: Let's Move It
Review Questions and Exercises
Programming Challenges
16. Exceptions, Templates, and the Standard Template Library (STL)
16.1 Exceptions
16.2 Fucntion Templates
16.3 Class Templates
16.4 Class Templates and Inheritance
16.5 Introduction to the Standard Template Library
16.6 Tying It All Together: Word Transformers Game
Review Questions and Exercises
Programming Challenges
17. Linked Lists
17.1 Introduction to the Linked List ADT
17.2 Linked List Operations
17.3 A Linked List Template*
17.4 Recursive Linked List Operations
17.5 Variations of the Linked List
17.6 The STL list Container*
17.7 Reliable Software Systems, Inc., Case Study
17.8 Tying It All Together: More on Graphics and Animation
Review Questions and Exercises
Programming Challenges
18. Stacks and Queues
18.1 Introduction to the Stack ADT
18.2 Dynamic Stacks
18.3 The STL stack Container*
18.4 Introduction to the Queue ADT
18.5 Dynamic Queues
18.6 The STL deque and queue Containers*
18.7 Focus on Problem Solving and Program Design: Eliminating Recursion
18.8 Tying It All Together: Converting Postfix Expressions to Infix
Review Questions and Exercises
Programming Challenges
19. Binary Trees
19.1 Definition and Applications of Binary Trees
19.2 Binary Search Tree Operations
19.3 Template Considerations for Binary Search Trees
19.4 Tying It All Together: Genealogy Trees
Review Questions and Exercises
Programming Challenges
APPENDICES
A: The ASCII Character Set
B: Operator Precedence and Associativity
C: Answers to Checkpoints
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18 - 19
D: Answers to Odd-Numbered Review Questions
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
INDEX
Symbols and Numerics
A
B
C
D - E
F
G
H - I
J - K - L
M - N
O
P
Q
R
S
T
U
V
W
Location of Videonotes in the Text
C++ Quick Reference
Recommend Papers

Starting Out with C++: Early Objects [9 ed.]
 0134400240, 9780134400242

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

start·ng out wi h >>>

EARLY OBJECTS T

DIT ON

Digital Resources for Students Your new textbook provides 12-month access to digital resources that may include VideoNotes (step-by-step video tutoria ls on programm ing concepts), source code, web chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of resources. Follow the instr uctions below to register for the Companion Website for Tony Gaddis, Judy Walters, and Godfrey Muganda's Staring Out with C ++: Early Objects, Ninth Edition . I. Go to www.pearso nhighered.com/cs - resources 2. Enter the t itle of your textboo k or browse by author name. 3. Click Companion Website 4. Click Register and follow the on-screen instructions to create a login name and password .

Use a coin to scratch off the coating and revea l your access code. Do not use a sharp knife or other sharp object as it may damage the code.

Use the login name and password you created during registration to start using t he d igital resources t hat accompany your textboo k.

IMPORTANT: This prepaid subscription does not include access to MyProgamminglab, which is available at www.myprog ramm inglab.com for purchase. This access code can only be used once. This subscription is valid for 12 months upon activation and is not transferrable. If the access code has already been revealed it may no longer be valid. If this is the case you can purchase a subscription on the login page for the Companion Website.

For tec hnical support go to http://247pea rsoned.cust help.com

This page intentionally left blank

LOCATION OF VIDEONOTES IN THE TEXT

~

VideoNote -

Chapter 1

Designing a Program with Pseudocode, p. 20 Designing the Account Balance Program, p. 25 Predicting the Output of Problem 30, p. 25 Solving the Candy Bar Sales Problem, p. 26

Chapter 2

Using cout to Display Output, p. 32 Assignment Statements, p. 59 Arithmetic Operators, p. 62 Solving the Restaurant Bill Problem, p. 74

Chapter 3

Using ci n to Read Input, p. 77 Evaluating Mathematical Expressions, p. 84 Combined Assignment Operators, p. 102 Solving the Stadium Seating Problem, p. 148

Chapter4

Using an if Statement, p. 161 Using an if I else Statement, p. 170 Using an if I else i f Statement, p. 176 Using Logical Operators, p. 189 Solving the Time Calculator Problem, p. 238

Chapter 5

The while Loop, p. 244 The for Loop, p. 271 Nested Loops, p. 279 Solving the Ocean Levels Problem, p. 317

Chapter6

Defining and Calling Functions, p. 324 Using Function Arguments, p. 333 Value-Returning Functions, p. 343 Solving the Markup Problem, p. 399

Chapter 7

Creating a Class, p. 412 Creating and Using Class Objects, p. 414 Creating and Using Structures, p. 454 Solving the Car Class Problem, p. 500

Chapter8

Accessing Array Elements, p. 509 Passing an Array to a Function, p. 543 Two-Dimensional Arrays, p. 553 Solving the Chips and Salsa Problem, p. 593

Chapter9

Performing a Binary Search, p. 606 Sorting a Set of Data, p. 613 Solving the Lottery Winners Problem, p. 641

-

(continued on next page)

LOCATION OF VIDEONOTES IN THE TEXT

-

-

(continued)

~

VideoNote

Chapter 10

Pointer Variables, p. 647 Dynamically Allocating an Array, p. 671 Solving the Days in Current Month Problem, p. 702

Chapter 11

Operator Overloading , p. 730 Aggregation and Composition, p. 776 Overriding Base Class Functions, p. 797 Solving the Number of Days Worked Problem, p . 811

Chapter 12

Converting Strings to Numbers , p. 829 Writing a C-String Handling Function, p. 833 Solving the Case Manipulator Problem, p. 850

Chapter 13

The get Family of Member Functions, p. 869 Rewinding a File, p. 873 Solving the File Encryption Filter Problem, p. 912

Chapter 14

Recursive Binary Search, p. 927 QuickSort, p. 929 Solving the Recursive Multiplication Problem, p. 947

Chapter 15

Polymorph ism, p. 955 Composition versus Inheritance, p. 969 Solving the Sequence Sum Problem, p. 985

Chapter 16

Throwing and Handling Exceptions, p. 988 Writing a Function Template, p. 1000 Iterators, p. 1017 Solving the Arithmetic Exceptions Problem, p. 1034

Chapter 17

Adding an Element to a Linked List, p. 1045 Removing an Element from a Linked List, p. 1052 Solving the Member Insertion by Position Problem, p. 1083

Chapter 18

Storing Objects in an STL Stack, p. 1097 Storing Obj ects in an STL Queue, p. 1111 Solving the File ReverserProblem, p. 1123

Chapter 19

Inserting an Element into a Binary Tree, p. 1132 Removing an Element from a Binary Tree, p. 1136 Solving the Tree Size Problem, p. 1152

Ninth Edition

C++ Early Objects

Tony Gaddis Judy Walters Godfrey Muganda

PEARSON Boston Columbus Indianapolis New York San Francisco Hoboken Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

Vice President, Editorial Director , ECS: Marcia Horton Acquisitions Editor: Ma tt Goldstein Editorial Assistant: Kristy Alaura Vice President of Marketin g: Christy Lesko Director of Field Marketing: Tim Ga lligan Product Mark eting Mana ger: Bram Van Kempen Field Marketin g Mana ger: Demetrius Ha ll Marketin g Assistant: Jon Bryant Director of Product Mana gement: Erin Gregg Tea m Lead, Program and Project Management: Scott Disanno Program Mana ger: Carole Snyder Project Mana ger: RPK Editorial Services, Inc.

Senior Specialist, Program Planning and Support: Maura Zaldivar -Garcia Cover Designer: Joyce Wells Cover: Sabyna 75/Shutterstock Mana ger, Right.s and Permissions: Rachel Youdelman Project Mana ger, Rights and Permissions: William Opa luch Inventory Mana ger: Meredith Maresca Media Project Mana ger: Renata Butera Full-Service Project Mana gement: Deepthi Mohan, Aptara® Corporation Compos ition: Aptara ® Corporation Printer/Binder: Edwar ds Brothers Mallo y, Inc. Cover and Insert Printer: Phoenix Color

Microsoft and/or its respective supp liers make no representations about the suitability of the information containe d in the documents and related graphics pub lished as part of the services for any purpose. All such documents and related graphics are provided "as is" without warranty of any kind. Microsoft and/or its respective supp liers hereby disclaim a ll warranties and conditions with regard to this information, including all warranties and conditions of merchantability , whether express, implied or statutory, fitness for a particular purpose, title and non -infringement. In no event shall Microsoft and/or its respective suppliers be liab le for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or otl1er tortious action, arising out of or in connection with the use or performance of information available from the services. The documents and related graphics contained herein could include technical inaccuracies or typograp hical errors. Changes are periodically added to the information herein. Microsoft and/or its respective supp liers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time. Partia l screen shots may be viewed in full within the software version specified. Microsoft® Windows®, and Microsoft Office® are registered trademarks of the Microsoft corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or affiliated with tl1eMicrosoft corporation. The programs and app lications 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. The pub lisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications. Copyright© 201 7, 2014 Pearson Education, Inc. All rights reserved. Manufactured in the United States of America. This pub lication is protected by Copyright, and permission should be obtained from the pub lisher prior to any prohibited reproduction, storage in a retrieva l system, or transmission in any form or by any means, electronic, mechanica l, photocopying, recording, or likewise. For information regarding permissions, request forms and the appropriate contacts within the Pearson Education Globa l Rights & Permissions department, please visit www.pearsonhig hed.com/permissions/. Many of the designations by manufacturers and sellers to distinguish their products are claimed as tra demarks. Where those designations appear in this book, and the pub lisher was aware of a trademark claim, the designations have been printe d in initial caps or all caps.

Library of Congress Cataloging-in-PublicationData Names: Gaddis, Tony. I Walters, Judy. I Muganda, Godfrey. Title: Starting out with C++. Early objects/ Tony Gaddis, Judy Wa lters, Godfrey Muganda. Description: Ninth edition. I Boston : Pearson, 201 7. I Includes index. Identifiers: LCCN 20150488 47 I ISBN 01344002 40 Subjects: LCSH: C++ (Computer program language) C lassification: LCC QA76.73.C153 G333 2017 1DOC 005.13/3-dc23 LC record availab le at htt p://lccn.loc.gov/20150488 47 10 9 8 7 6 5 4 3 2 1

PEARSON

ISBN 10: 0-13-440024 -0 ISBN 13: 978 -0-13-440024 -2

"

Preface

xv

Chapter

1

Introduction

to Computers

and Programming

Chapter

2

Introduction

to C++

Chapter Chapter

3 4

Expressions and Interactivity Making Decisions 155

Chapter

5

Looping

Chapter

6

Functions

Chapter Chapter

7 8

Introduction to Classes and Objects 507 Arrays

Chapter

9

Searching,

1

27 77

243 323

Sorting , and Algorithm

407 Analysis

Chapter Chapter Chapter

10 11 12

Pointers 645 More about Classes and Object -Oriented More on ( -Strings and the string Class

Chapter

13

Advanced

Chapter Chapter

14 15

Recursion 915 Polymorphism and Virtual Functions

Chapter

16

Exceptions,

Chapter Chapter

17 18

Linked Lists 103 7 Stacks and Queues 1085

Chapter

19

Binary Trees

File and 1/ 0 Operations

Templates,

603

Programming 815

703

853

and the Standard

949

Template

Library (STL)

1125

Appendix Appendix

A: The ASCII Character Set 1155 B: Operator Precedence and Associativity

Appendix Appendix

C: Answers to Checkpoints 1161 D: Answers to Odd -Numbered Review Questions

Index

987

1159 1201

1221

V

This page intentionally left blank

dumperina

Preface CHAPTER 1

1.1 1.2 1.3 1.4 1.5 1.6 1.7 CHAPTER 2

2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 2.13 2.14 2.15 2.16 2.17 2.18

xv

Introduction

to Computers and Programming

Why Program? 1 Computer Systems: Hardware and Software Programs and Programming Languages 8 What Is a Program Made of? 13 Input, Processing, and Output 17 The Programming Process 18 Tying It All Together: Hi! It 's Me 23 Introduction

to C++

1

3

27

The Parts of a C++ Program 2 7 The cout Object 31 The# i ncludeDirect ive 36 Variables and the Assignment Statement 37 Literals 39 Identifiers 41 Integer Data Types 43 Floating-Point Data Types 48 The char Data Type 52 TheC++str i ngClass 56 The bool Data Type 57 Determining the Size of a Data Type 58 More on Variable Assignments and Initialization Scope 61 Arithmetic Operators 62 Comments 66 Programming Style 67 Tying It All Together: Smile! 69

59

vii

v iii

Contents CHAPTER 3

3 .1 3 .2 3 .3 3.4 3 .5 3 .6 3 .7 3 .8 3 .9 3 .10 3 .11 3 .12 3 .13 CHAPTER 4

4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15 4.16 CHAPTER 5

5 .1 5 .2 5.3 5.4 5 .5 5 .6 5 .7

Expressions and Interactivity

77

ThecinObject 77 Mathematical Expressions 84 Data Type Conversion and Type Casting 92 Overflow and Underflow 98 Named Constants 99 Multiple and Combined Assignment 102 Formatting Output 106 Working with Characters and Strings 116 More Mathematical Library Functions 130 Random Numbers 132 Focus on Debugging: Hand Tracing a Program 136 Green Fields Landscaping Case Study- Part 1 138 Tying It All Together: Word Game 141 Making Decisions

155

Relational Operators 155 The if Statement 161 Theif/elseStatement 170 The if /else if Statement 175 Menu-Driven Programs 183 Nested i f Statements 185 Logical Operators 189 Validating User Input 198 More about Blocks and Scope 200 More about Characters and Strings 203 The Conditional Operator 209 The switch Statement 213 Enumerated Data Types 222 Focus on Testing and Debugging: Validating Output Results Green Fields Landscaping Case Study- Part 2 227 Tying It All Together: Fortune Teller 232 Looping

243

Introduction to Loops: The whi le Loop 243 Using the while Loop for Input Validation 250 The Increment and Decrement Operators 253 Counters 258 Keeping a Running Total 260 Sentinels 263 The do-while Loop 265

225

Contents

5 .8 5 .9 5 .10 5 .11 5 .12 5 .13 5 .14 5 .15 CHAPTER 6

6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 6.15 6.16 6.17 6.18 CHAPTER 7

7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 7.11

The for Loop 271 Focus on Software Engineering: Deciding Which Loop to Use 277 Nested Loops 279 Breaking Out of a Loop 281 Using Files for Data Storage 285 Focus on Testing and Debugging: Creating Good Test Data 301 Central Mountain Credit Union Case Study 304 Tying It All Together: What a Colorful World 308 Function s

323

Modular Programming 323 Defining and Calling Functions 324 Function Prototypes 332 Sending Data into a Function 333 Passing Data by Value 338 The return Statement 342 Returning a Value from a Function 343 Returning a Boolean Value 349 Using Functions in a Menu-Driven Program 351 Local and Global Variables 355 Static Local Variables 362 Default Arguments 364 Using Reference Variables as Parameters 368 Overloading Functions 378 The exit() Function 382 Stubs and Drivers 385 LittleLottoCaseStudy 387 Tying It All Together: Glowing Jack-o-lantern 392 Introduction

to Classes and Objects

407

Abstract Data Types 407 Object-Oriented Programming 409 Introduction to Classes 411 Creating and Using Objects 414 Defining Member Functions 416 Constructors 423 Destructors 429 Private Member Functions 432 Passing Objects to Functions 435 Object Composition 442 Focus on Software Engineering: Separating Class Specification, Implementation , and Client Code 446

ix

x

Contents 7.12 7.13 7.14 7.15 7.16 7.17 CHAPTER 8

8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 8.10 8.11 8.12 8.13 8.14 8.15 CHAPTER 9

9 .1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 CHAPTER 10

10.1 10.2 10.3

Structures 453 More about Enumerated Data Types 465 Home Software Company OOP Case Study 469 Introduction to Object-Oriented Analysis and Design 476 Screen Contro l 486 491 Tying It All Together: Yoyo Animation Arrays

507

Arrays H old Multiple Values 507 Accessing Array Elements 509 Inputting and Displaying Array Data 511 Array Initialization 518 The Range-Based for loop 525 Processing Array Contents 528 Using Parallel Arrays 539 The typede f Statement 543 Arrays as Function Arguments 543 Two-Dimensional Arrays 553 Arrays with Three or More Dimensions 560 Vectors 563 Arrays of Objects 575 National Commerce Bank Case Study 585 Tying It All Together: Rock, Paper, Scissors 587 Searching, Sorting , and Algorithm Analysis

Introduction to Search Algorithms 603 Searching an Array of Objects 610 Introduction to Sorting Algorithms 613 Sorting an Array of Objects 621 Sorting and Searching Vectors 624 Introduction to Analysis of Algorithms 627 Case Studies 635 Tying It All Together: Secret Messages 635 Pointers

645

Pointers and the Address Operator 645 Pointer Variables 647 The Relationship Between Arrays and Pointers 651

603

Contents

10.4 10.5 10.6 10. 7 10.8 10.9 10.10 10.11 10.12 10.13 10.14 CHAPTER 11

11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 11.10 11.11 11.12 11.13 11.14 11.15 11.16 CHAPTER 12

12.1 12.2 12.3 12.4 12.5 12.6 12.7

Pointer Arithmetic 655 Initializing Pointers 656 Comparing Pointers 659 Pointers as Funct ion Parameters 661 Pointers to Constants and Constant Pointers 665 Focus on Software Engineering: Dynamic Memory Allocation 670 Focus on Software Engineering: Returning Pointers from Functions 674 Pointers to Class Objects and Structures 680 Focus on Software Engineering: Selecting Members of Objects 684 Smart Pointers 686 Tying It All Together: Pardon Me, Do You Have the Time?

694

More about Classes and Object -Oriented Programming

The th is Pointer and Constant Member Functions 703 Static Members 708 Friends of Classes 715 Memberwise Assignment 720 Copy Constructors 721 Operator Overloading 730 Rvalue References and Move Operations 751 Function Objects and Lambda Expressions 761 Type Conversion Operators 770 Convert Constructors 773 Aggregation and Composition 776 Inheritance 782 Protected Members and Class Access 787 Constructors, Destructors, and Inheritance 792 Overr iding Base Class Functions 797 Tying It All Together: Putting Data on the World Wide Web More on C-Strings and the s t ring Class

815

C-Strings 815 Library Functions for Working with C-Strings 820 Conversions Between Numbers and Strings 829 Writing Your Own C-String Handling Functions 833 More about the C++ str i ng Class 839 Advanced Software Enterprises Case Study 842 Tying It All Together: Program Execution Environments

844

703

800

xi

xii

Contents

CHAPTER13 13.1 13.2 13.3 13.4 13.5 13.6 13. 7 13.8 13.9

CHAPTER14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 14.10

CHAPTER15 15.1 15.2 15.3 15.4 15.5 15.6

CHAPTER16 16 .1 16.2 16.3 16.4 16.5 16.6

Advanced File and 1/ 0 Operations

853

Input and Output Streams 853 More Detailed Error Testing 861 Member Functions for Reading and Writing Files 865 Binary Files 877 Creating Records with Structures 881 Random -Access Files 886 Opening a File for Both Input and Output 893 Online Friendship Connections Case Study: Object Serialization 898 Tying It All Together : File Merging and Color-Coded HTML 903

Recursion

915

Intr oduct ion to Recursion 915 The Recursive Factorial Function 922 The Recursive gcd Function 924 Solving Recursively Defined Problems 925 A Recursive Binary Search Function 927 Focus on Problem Solving and Program Design: The QuickSort Algorithm 929 The Towersof Hano i 933 Focus on Problem Solving: Exhaustive and Enumeration Algorithms 936 Focus on Software Engineering: Recursion versus Iteration 940 Tying It All Together : Infix and Prefix Expressions 941

Polymorphism

and Virtual Functions

949

Type Compatibi lity in Inheritance Hierarchies 949 Polymorp hism and Virtual Member Functions 955 Abstract Base Classes and Pure Virtual Functions 963 Focus on Object -Oriented Programming : Composition versus Inheritance Secure Encryption Systems, Inc., Case Study 973 Tying It All Together : Let's Move It 976

Exceptions, Templates, and the Standard Template Library (STL) 987 Exceptions 987 Function Templates 999 Class Templates 1007 Class Templates and Inheritance 1012 Intr oduct ion to the Standard Templat e Library 1016 Tying It All Together : Word Transformers Game 1029

969

Contents

CHAPTER 17

17.1 17.2 17.3 17.4 17.5 17.6 17. 7 17.8 CHAPTER 18

18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8 CHAPTER 19

19.1 19.2 19.3 19.4

Linked Lists

1037

Introduction to the Linked List ADT 1037 Linked List Operations 1043 A Linked List Template 1055 Recursive Linked List Operations 1059 Variations of the Linked List 1067 The STL list Container 1068 Reliable Software Systems, Inc., Case Study 1071 Tying It All Together: More on Graphics and Animation Stacks and Queues

1074

1085

Introduction to the Stack ADT 1085 Dynamic Stacks 1093 The STL stack Container 1097 Introduction to the Queue ADT 1099 Dynamic Queues 1106 The STL deque and queue Containers 1109 Focus on Problem Solving and Program Design: Eliminating Recursion Tying It All Together: Converting Postfix Expressions to Infix 1117 Binary Trees

1112

1125

Definition and Applications of Binary Trees 1125 Binary Search Tree Operations 1129 Template Considerations for Binary Search Trees 1145 Tying It All Together: Genealogy Trees 1145 Appendix A: Appendix B: Appendix C: Appendix D: Index 1221

The ASCII Character Set 1155 Operator Precedence and Associativity 1159 Answers to Checkpoints 1161 Answers to Odd -Numbered Review Questions

1201

x iii

xi v

Contents

Additional Appendices The following append ices are located on the book's compan ion web site. Appendix E: A Brief Introduction to Object -Oriented Programming Appendix F: Using UMLin Class Design Appendix G: Multi-Source File Programs Appendix H: Multiple and Virtual Inheritance Appendix I: Header File and Library Function Reference Appendix J: Namespaces Appendix K: C++ Casts and Run-Time Type Identification Appendix L: Passing Command Line Arguments Appendix M: Binary Numbers and Bitwise Operations Appendix N: Introduction to Flowcharting

Welcome to Starting Out with C++:Early Objects, 9th Edition . This book is intended for use in a two -term or three -term C++ programming sequence, or an accelerated one-term course. Students new to programming, as well as those with prior course work in other languages, will find this text beneficial. The fundamentals of programming are covered for the novice, while the details, pitfalls, and nuances of the C++ language are explored in-depth for both the beginner and more exper ienced student . T he book is written with clear, easy-to -understand language and it covers all the necessary topics for an introductory programming course. T his text is rich in example programs that are concise, practica l, and real world oriented, ensuring that the student not only learns how to implement the features and constructs of C++, but why and when to use them.

What's New in the Ninth Edition The New C++ 11 Standard

C++11 is the latest standard version of the C++ language . In previous years, while the standard was being developed, it was known as C++Ox. In August 2011, it was approved by the International Standards Organization (ISO), and the name of the standard was officially changed to C++l l. Most of the popular C++ compilers now support this standard. T he new C++ 11 standard was the primary motivat ion behind this edition, which introduces many of the new language features. H owever, a C++11 compi ler is not strictly required to use the book . As you progress through the book, you will see C++ll icons in the marg ins, next to the new features that are introduced . Programs appearing in sections that are not marked with this icon will still compi le using an older compiler. The C++ 11 Topics Introduced in This Edition

• The aut o key word is introduced in Chapter 2 as a way to simplify comp lex variable definitions . This key word causes the comp iler to infer a variable's data type from its initializat ion value.

xv

xvi

Preface

• Chapter 2 also introduces the new long long i nt and unsigned long long i nt data types and the LL literal suffix. • Chapter 5 shows how to pass a str i ng object directly to a file stream object's open member function, without the need to call the c_s t r () member function. A discussion of the c_s t r () function sti ll exists for anyone using a legacy compiler. • Th e range -based for loop is introduced in Chapter 7 . Thi s new looping mechanism automatically iterates over each element of an array, vector, or other collect ion, without the need for a counter variable or a subscr ipt. • Chapter 7 also introduces strongly typed enums. • Chapter 8 introduces new ways to initialize variables and shows how a vec t or can now be initialized with an initia lization list. • Chapter 10 introduces smart pointers and provides examples of how and why to use the new uni que_ptr and shared_ptr pointers for safely allocating and working with dynamic memory . • Chapter 10 also introduces the move assignment operator, and the null pt r key word, which is now the standard way of representing a null pointer. • Chapter 11 discusses move constructors, provides more in depth coverage of move assignment operators, and introduces lambda expressions . • Chapter 12 introduces new functions in the C++ 11 string library and discusses the new overloaded to _stri ng functions for convert ing numeric values to stri ng ob jects. • Chapter 15 introduces and demonstrates the use of the new override key word that helps prevent subtl e over ridin g errors and the new final key word that prevents a virtua l member function from being overridden . • Chapter 16 introduces the new C++ 11 functions begi n ( c) and end ( c) to specify positions within a collection c where an operat ion shou ld begin and end. What Else is New

This book's pedagogy and clear writing style remain the same as in the previous edition. However, in addition to upd at ing the book to introduce the new C++l 1 standard, many improvements have been made to make it even more student -friendly. • Upd ated Material Material has been upd ated throughout the book to reflect changes in technology and in software development environments, as well as to improve clarity and incorporate best practices in teaching introductory programming . As a resu lt, new graphics and new or redesigned figures have been added throughout the book where appropriate and new or impr oved sample programs have been included in a number of chapters . • New Material New materia l has been added on a number of topics. In add ition to introducing and using new C++ 11 features, this new edition includes new sections on literals, random numbers, and enumerated data types, as well as improved materia l on designing classes.

Preface

• New Programming Challenges New Programming Challenge problems have been added to every chapter. • Reorganized Chapters

Several chapters have been redesigned to improve student learning . Chapter 5 (Looping) has been reorganized to give st udents more practice using the whi le loop before introducing do-while and for loops. The Chapter 6 (Fun ctions) material on defining and calling functions has been reorganized to introduce function prototypes earl ier and allow main to always be the first function in a client program .

Organization

of the Text

Thi s text teaches C++ in a step -by-step fashion. Each chapte r covers a major set of topics and builds knowledge as the student progresses through the book . Although the chapters can be easily taught in their existing sequence, flexibility is provided . The following dependency diagram (Figur e P-1) suggests possible sequences of instruct ion . Chapter 1 covers fundamental hardware, software, and programm ing concepts. The instructor may choose to skip this chapter if the class has already mastered those topics. Chapters 2 through 6 cover basic C++ syntax, data types, expressions, selection str uctures, repetition str uctures, and functions . Each of these chapters builds on the previous chapter and should be covered in the order presented. Chapter 7 introduces object -oriented programming . It can be covered any time after Chapter 6, but before Chapter 11. Instructors who prefer to introduce arrays before classes can cover Chapter 8 before Chapter 7 . In this case it is only necessary to postpone Section 8.13 (Arrays of Objects) until Chapter 7 has been covered. As Figure P-1 illustrates, in the second half of the book Chapters 11, 12, 13, and 14 can be covered in any order. Chapters 11, 15, and 16, however, shou ld be done in sequence. Instructors who wish to introduce data structures at an earlier point in the course, without having first covered advanced C++ and OO P features, can cover Chapter 17 (Linked Lists), followed by Chapters 18 and 19 (Stacks & Queues and Binary Tr ees), any time after Chapter 14 (Recursion). In this case it is necessary to simply omit the sections in Chapters 17- 19 that deal with templates and the Standard Template Library.

xvii

xviii

Preface

Figure P-1 Chapter1 Introduction

..



Chapters2-6 Basic Language Elements



I

Chapter7 OOP Introduction

Chapter8 Arrays

+

I

+

Chapter9 Searching, Sorting, and AlgorithmAnalysis

Chapter10 Pointers

I

+ Chapter11 MoreOOP

• •



Chapter12 Advanced Strings

I

• •

+

Chapter13 AdvancedFiles and 1/0

Chapter14 Recursion

Chapter15 Adv.OOP

Chapter16 Exceptions, Templates , and STL

Chapter17 LinkedLists

+

Chapter18 Stacksand Queues

I

+ Chapter19 BinaryTrees

Preface

Brief Overview of Each Chapter Chapter 1: Introduction to Computers and Programming T his chapter prov ides an introduction to the field of computer science and covers the fundamentals of hardware , software, operating systems, programming, problem so lving, and software engineering . The components of programs, such as key words, variables, operators, and punctuation are covered . The tools of the trade , such as hierarchy charts and pseudocode, are also presented . T he Tying It All T ogether sect ion shows students how to use the cout statement to create a personalized output message. Programm ing Challenges at the end of the chapter help students see how the same basic input, processing , and output structure can be used to create multiple programs .

Chapter 2: Introduction to C++ This chapter gets the student started in C++ by introducing the basic parts of a C++ program , data types, the use of variables and literals, assignment statements, simple arithmetic operations, program output, and comments . T he C++ s t ring class is presented and string objects are used from this point on in the book as the primary method of handling strings. Programm ing sty le conventions are introduced , and good programming style is modeled here, as it is throughout the text . The Tying It All T oget her section lets the student play with simple text based graphics.

Chapter 3: Expressions and Interactivity In this chapter the student learns to write programs that input and hand le numer ic, character, and string data. The use of arithmet ic operators and the creation of mathemat ica l expressions are covered, with emphasis on operator precedence . Debugging is introduced, with a section on hand tracing a program . Sections are also included on using random numbers , on simp le output formatting, on data type conversion and type casting, and on using library functions that work with numbers. The Tying It All T ogether section shows students how to create a simple interactive word game.

Chapter 4: Making Decisions Here the student learns about relationa l expressions and how to control the flow of a program with if, if I else , and if I else i f statements . Logical operators, the cond itional operator, and the swi tch statement are also covered . Applications of these constructs, such as menu -driven programs , are illustrated . This chapter also introduces the concepts of blocks and scope and continues the theme of debugging with a section on validating output results. The Tying It All T ogether section uses random numbers and branching statements to create a fortune telling game.

xix

xx

Preface

Chapter 5: Looping This chapter introduces, C++'s repetitive control mechanisms . The while loop, do-while loop, and for loop are presented, along with a variety of methods to control them . These include using counters, user input, end sentinels, and end-of-file testing. Applications utilizing loops, such as keeping a running total and performing data validation, are also covered . The chapte r includes an extensive section on working with files and a section on creating good test data, continuing the book's emphasis on testing and debugging. The Tying It All Together section introduces students to Windows commands to create colorful output and uses a loop to create a multi-colored display .

Chapter 6: Functions In this chapter the student learns how and why to modularize programs, using both void and value-returning functions. Parameter passing is covered, with emphasis on when arguments shou ld be passed by value versus when they need to be passed by reference. Scope of variables is covered and sections are provided on local versus globa l variables and on static local variables . Overloaded functions are also introduced and demonstrated . The Tying It All Together section includes a modular, menu -driven program that emphasizes the versatility of functions, illustrating how their behavior can be controlled by the arguments sent to them .

Chapter 7: Introduction to Classes and Objects In this chapter the text begins to focus on the object-oriented paradigm . Students have used provided C++ classes since the beginning of the text, but now they learn how to define their own classes and to create and use objects of these classes. Careful attention is paid to illustrating which functions belong in a class versus which functions belong in a client program that uses the class. Good object-oriented practices are discussed and modeled, such as protecting member data through carefully constructed accessor and mutator functions and hiding class implementation details from client programs. Once students are comfortable working with classes and objects, the chapter provides a brief introduction to the topic of object-oriented analysis and design. The chapter also includes a section on enumerated data types and a section on structures, which are used in the Tying It All Together section, where students learn to use screen control techniques to create a yoyo animation .

Chapter 8: Arrays In this chapter the student learns to create and work with single and multidimensional arrays. Many examples of array processing are provided, including functions to compute the sum, average, highest and lowest values in an array . Students also learn to create tables using two -dimensional arrays, and to analyze array data by row or by column . Programming techniques using parallel arrays are also demonsrrated, and the student is shown how to use a data file as an input source to populate an array . The range -based for loop is introduced as an easy way to iterate through all the elements of an array, and STL vectors are introduced and compared to arrays. A section on arrays of objects and structures is located at the end of the chapter, so it can be covered now or saved for later if the instructor wishes to cover this chapter before Chapter 7. The Tying It All Together section uses arrays to create a game of Rock, Paper, Scissors between a human player and the computer.

Preface

Chapter 9: Searching, Sorting, and Algorithm Analysis Here the student learns the basics of searching for information stored in arrays and of sorting arrays , including arrays of objects. The chapter covers the Linear Search, Binary Search, Bubble Sort, and Selection Sort algo rithm s and has an optional section on so rtin g and search ing STL vecto rs. A brief int rod uction to algorithm analysis is included, and students are shown how to determine which of two algorithms is more efficient . Thi s chapter's Tying It All T ogether section uses both a table lookup and a searching algorithm to encode and decode secret messages.

Chapter 10: Pointers Thi s chapter explains how to use pointers . T op ics include pointer arithmetic, initialization of pointers , comparison of pointers, pointers and arrays, pointers and funct ions, dynamic memory allocation , the new null pt r key word, and more . A new section introduces smart pointers and shows how they can be used to avoid memory leaks. Th e Tying It All T oget her section demonstrates the use of pointers to access library data struct ures and fun ctions that ret urn calendar and wall cloc k time.

Chapter 11: More About Classes and Object -Oriented Programming This chapter contin ues the study of classes and object-oriented programming, covering more advanced topics such as inheritan ce and object aggregat ion and compos ition. Other topics include constant member functions , static members, friends, memberwise assignment, copy constructors, object type conversion operators, convert constr uctors, operator overloading, move constr uctors, and move assignment operators . A new section introduces function objects and the C++ll lambda expressions. The Tying It All Together section brings together the concepts of inheritance and convert constr uctors to build a program that formats the contents of an array to form an HTML tab le for display on a Web site.

Chapter 12: More on (-Strings and the string

Class

Thi s chapter covers standard library functions for working with characters and C-strings, as well as materia l on str i ng class functions , functions in the new C++11 string library, and new overloaded to_st ring functions for converting numeric values to str i ng objects . Th e Tying It All T ogether section shows students how to access string -based program environments to obtain information about the computer and the network on which the program is runnin g.

Chapter 13: Advanced File and 1/ 0 Operations Thi s chapte r intr oduces more advanced topics for work ing with sequential access text files and introduces random access and binary files . Various modes for open ing files are disc ussed, as well as the many methods for reading and writing their contents. Th e Tying It All T oget her program app lies many of the techniques covered in the chapte r to merge two text files into an HTML doc ument for display on the Web , with different colors used to illustrate which file each piece of data came from .

xxi

xxii

Preface

Chapter 14: Recursion In this chapter recursion is defined and demonstrated . A visual trace of recursive calls is provided, and recursive applications are discussed . Many recursive algorithms are presented, includ ing recursive functions for computing factorials, finding a greatest common denom inator (GCD), performing a binary search, sorting using QuickSort, and solving the famous Towers of Hanoi problem . For students who need more challenge, there is a section on exhaustive and enumeration algorithm s. The Tying It All Together section uses recursion to evaluate prefix expressions .

Chapter 15: Polymorphism and Virtual Functions The study of classes and object -oriented programming continues in this chapter with the introduction of more advanced concepts such as polymorphism and virtual functions. Information is also presented on abstract base classes, pure virtual functions, type compatibi lity within an inheritance hierarchy, and virtua l inheritance . The Tying It All Together section illustrates the use of inheritance and polymorphism to display and animate graphica l images.

Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) Here the student learns to develop enhanced error trapping techniques using exceptions. Discussion then turns to using funct ion and class templates to create gener ic code . Finally, the student is introduced to the containers, iterators, and algorithms offered by the Standard Template Library (STL). The Tying It All Together section uses various conta iners in the Standard Template Librar y to create an educational children's game.

Chapter 17: Linked Lists This chapter introduces concepts and techniques needed to work with lists. A linked list ADT is developed, and the student learns how to create and destroy a list, as well as to write functions to insert, append, and delete nodes, to traverse the list, and to search for a specific node. A linked list class template is also demonstrated. The Tying It All Together section brings together many of the most important concepts of OOP by using objeets, inheritance, and polymorphism in conjunction with the STL list class to animate a collection of images.

Chapter 18: Stacks and Queues In this chapter the student learns to create and use stat ic and dynamic stacks and queues. Th e operations of stacks and queues are defined, and templates for each ADT are demonstrated . The stat ic array -based stack uses exception -handling to handle stack overflow and und erflow, providing a realistic and natural example of defining, throwing, and catching except ions . The Tying It All Together section discusses strateg ies for evaluating postfix expressions and uses a stack to convert a postfix expression to infix.

Chapter 19: Binary Trees This chapter covers the binary tree ADT and demonstrates many binary tree operat ions. The student learns to traverse a tree, insert, delete, and replace elements, search for a particular element, and destroy a tree. The Tying It All Together section introduces a tree structure versatile enough to create genealogy trees.

Preface

Appendices in the Book Appendix A: The ASCII Character Set

A list of the ASCII and extended ASCII

characters and their codes. Appendix B: Operator Precedence and Associativity

A list of the C++ operators

with their precedence and associat ivity. A too l students can use to assess their under standing by comparing their answers to the Checkpoint exercises found throughout the book. The answers to all Checkpoint exercises are included.

Appendix C: Answers to Checkpoints

Appendix D: Answers to Odd-Numbered Review Questions Another too l students

can use to gauge their understanding and progress.

Additional Appendices on the Book's Companion Website Appendix E: A Brief Introduction

to Object -Oriented

Programming

An

introduction to the concepts and terminology of object-oriented programming . Appendix F: Using UML in ClassDesign A brief introduction to the Unified Modeling

Language (UML) class diagrams with examples of their use. A tutor ial on how to create, comp ile, and link programs with multiple source files. Includes the use of function header files, class specification files, and class implementat ion files.

Appendix C: Multi -Source File Programs

A self-contained discussion of the C++ concepts of multiple and virtual inheritance for anyone already familiar with single inheritance .

Appendix H: Multiple and Virtual Inheritance

Appendix I : Header File and Library Function Reference

A reference for the C++

library functions and header files used in the book. An explanation of namespaces and their purpose , with examples provided on how to define a namespace and access its members .

Appendix / : Namespaces

An introduction to different ways of doing type casting in C++ and to run -time type identificat ion.

Appendix K: C++ Casts and Run-Time Type Identification

An introduction to writing C++ programs that accept command -line arguments. This appendix will be useful to students working in a command -line environment, such as UNIX or Linux.

Appendix L: Passing Command Line Arguments

A guide to the binary number system and the C++ bitwise operators, as well as a tutorial on the internal storage of integers.

Appendix M : Binary Numbers and Bitwise Operations

A tutoria l that introduces flowcharting and its symbols . It includes hand ling sequence, selection, case, repetition , and calls to other modu les . Samp le flowcharts for several of the book's example programs are presented.

Appendix N: Introduction to Flowcharting

xxiii

xxiv

Preface

Features of the Text Concept Statements

Each major section of the text starts with a concept statement. This statement summarizes the key idea of the section.

Example Programs

The text has over 350 complete example programs, each designed to highlight the topic curr ently being studied . In most cases, these are practical, real-world examples . Source code for these programs is provided so that students can run the programs themselves.

Program Output

After each example program there is a samp le of its screen output. This immediately shows the student how the program should function.

Tying It All Together

This special section, found at the end of every chapter, shows the student how to do something clever and fun with the materia l covered in that chapter.

VideoNotes

A series of online videos, developed specifically for this book, are availab le for viewing at ht tp://www . pearsonhighered. com/cs-resources/. VideoNote icons appear throughout the text, alertin g the student to videos about specific topics .

~

Checkpoints

0

Checkpoints are questions placed throughout each chapter as a selftest study aid. Answers for all Checkpoint questions are provided in Appendix C at the back of the book so students can check how well they have learned a new topic .

Notes

Notes appear at app ropriate places throughout the text. They are short explanat ions of interesting or often misunderstood points relevant to the topic at hand .

(D

Warnings

Warnings caution the st udent abo ut certa in C++ features, programming techniques, or practices that can lead to malfunctioning programs or lost data .

Case Studies

Case studies that simulate real-world applications appear in many chapters throughout the text, with complete code provided for each one. Additional case studies are provided on the book's companion website. These case studies are designed to highlight the major topics of the chapter in which they appear.

Review Questions and Exercises

Each chapter presents a thorough and diverse set of review questions, such as fill-in-the-blank and short answer, that check the student' s mastery of the basic materia l presented in the chapter. These are followed by exercises requiring problem solving and analysis, such as the Algorithm Workbench, Predict the Output, and Find the Errors sections. Each chapter ends with a Soft Skills exercise that focuses on communication and group process skills. Answers to the odd numbered review questions and review exercises are provided in Appendix D at the back of the book .

a

VideoNot e

Preface Programming Challenges

Each chapter offers a pool of programming exercises designed to solidify the st udent' s know ledge of the topics curr ently being stud ied. In most cases the ass ignm ents present real-world prob lems to be solved .

Group Projects

There are several group programming projects throughout the text, intended to be constructed by a team of student s. One student might build the program's user interfa ce, while another student writes the mathematica l code, and another designs and implements a class the program uses. Thi s process is similar to the way many professiona l programs are written and encourages teamwork within the classroom .

C++ Quick Reference Guide

For easy access, a quick reference guide to the C++ language is printed on the inside back cover.

Supplements Student Resources Th e fo llowing items are avai lab le on the Gaddis Series resource www.pearsonhighered .com/cs-resources: • • • • •

page at

Complete source code for every program included in the book Additional case studies, complete with source code A full set of append ices (including several tutorials) that accompany the book Access to the book's companion VideoNotes Links to down load numerous programming environments and IDEs, including Visual Studio Community Edition .

Instructor Resources The following supplements are available to qualified instructors on ly. • • • • • •

Answers to all Review Questions in the text Solutions for all Programming Challenges in the text PowerPoint presentation slides for every chapte r A compute rized test bank A collection of lab materials Source code files

Visit the Pearson Education Instructor Resource Center (http://www.pearsonhighered.com/irc) for information on how to accessthem.

Practice and Assessment with MyProgramminglab MyProgrammingLab helps student s fully grasp the logic, semantics, and syntax of programming . Thr ough practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning student s who often struggle with the basic concepts and paradigms of popular high -level programming languages. A self-study and homework tool, MyProgrammingLab consists of hundreds of small practice exercises organized aro und the structure of this

xxv

xxvi

Preface

textbook. For students, the system automat ically detects errors in the logic and syntax of their code submissions and offers targeted hints that help them figure out what went wrong. For instructors, a comprehens ive gradeboo k tracks correct and incorrect answers and stores the code input by students for review. MyProgrammingLab is offered to users of this book in partnership with Turing's Craft, the makers of the CodeLab inter active programming exercise system . For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www .myprogramminglab .com. Which Gaddis C++ book is right for you?

T he Starting Out with C++ Series includes three books, one of which is sure to fit your course: • Starting Out with C++:Early Objects • Starting Out with C++:From Control Structures through Objects • Starting Out with C++:Brief Version

Preface

Acknowledgments T here have been many helping hand s in the development and publication of this text. We would like to thank the following faculty reviewers for their helpful suggestions and expertise.

Reviewers of the Ninth Edition or Its Previous Versions Ahmad Abuhejleh Fred M . D' Angelo University of Wisconsin, Riv er Falls Pima Community College David Akins Joseph DeLibero El Camino College Arizona State University Steve Allan Dennis Fairclough Utah State University Utah Valley State College Ijaz A. Awan Larry Farrer Savannah State University Guilford T echnical Community College John Bierbauer James D. Fitzgerald N orth Central College Golden West College Don Biggerstaff Richard Flint Fayetteville Technical Community North Central College College Sheila Foster Paul Bladek California State University Long Beach Spokane Falls Community College David E. Fox Chuck Boehm American River College Dean Foods, In c. Cindy Fry Bill Brown Baylor University Pikes Peak Community College Peter Gacs Richard Cacace Boston University Pensacola Juni or College Cristi Gale Randy Campbell Sterling College Morningside College James Gifford Stephen P. Carl University of Wisconsin, Stevens Point Wright State University Leon Gleiberman Wayne Caruolo Touro College Red Rocks Community College Simon Gray Thomas Cheatham Ashland University-Ohio Middle Tennessee State University Margaret E. Guertin James Chegwidden Tufts University Tarrant County College Jamshid Ha ghighi John Cigas Guilford T echnical Community College Rockhurst University Ranette H. Halverson John Cross Midwestern State University, Indiana University of Pennsylvania Wichita Falls, TX

xxvii

xxviii

Preface

Dennis Heckman Portland Community College

Bill Martin Central Piedmont Community College

Ric Heishman Northern Virginia Community College

Svetlana Marzelli Atlantic Cape Community College

Patricia Hines Brookdale Community College

Debbie Mathews ]. Sargeant Reynolds

Mike Holland Northern Virginia Community College

Ron McCarty Penn State Erie, Th e Behrend College

Lister Wayne Horn Pensacola Juni or College

Robert McDona ld East Stroudsburg University

Richard Hull Len oir-Rhyne College

James McGuffee Austin Community College

Norman Jacobson University of California, Irvine

M . Dee Med ley Augusta State University

Eric Jiang San Diego State University

Barbara Meguro University of Hawaii- Hilo

Yinping Jiao South T exas College

Cathi Chambley -Miller Aiken Technical College

Neven Jurkovic Palo Alto College

Sandeep Mitra SUN¥ Brockp ort

David Kaeli Northeastern University

Churairat O'Brien Columbia Basin College

Chris Kardaras North Central College

Frank Paiano Southwestern Community College

Amitava Karmaker University of Wisconsin- Stout

Jennifer Parham -Mocello Oregon State University

Eugene Katzen Montgomery College- Rockvi lle

Theresa Park Texas State Technical College

Willard Keeling Blue Ridge Community College

Mark Parker Shoreline Community College

A. J. Krygeris Houston Community College

Robert Plantz Sonoma State University

Ray Larson Inv er Hills Community College

Tino Posillico SUN¥ Farmingdale

Stephen Leach Florida State University

Mahmoud K. Quwe ider University of T exas at Brown sville

Parkay Louie Houston Community College Zhu -qu Lu University of Maine, Presque Isle

M . Padmaja Rao Francis Marion University Timothy Reeves San Juan College

Tucjer Maney George Mason University

Nancy Ripplinger North Idaho College

Preface Rona ld Robison Arkansas Tech University Caro line St. Clair North Central College Dolly Samson Weber State University Kate Sanders Rhode Island College T im Scheemaker Onondaga Community College Lalchand Shimpi Saint Augustine 's College Sung Shin South Dakota State University Barbara A. Smith University of Dayton Garth Sorenson Snow College Donald Southwell Delta College Daniel Spiegel Kutztown University Ray Springston University of Texas at Arlington KirkStephens Southwestern Community College Cherie Stevens South Florida Community College Joe Struss Des Moines Area Community College Hong Sung University of Central Oklahoma

Sam Y. Sung South Texas College Mark Swanson Red Wing Technical College Martha Tillman College of San Mateo Maya Tolappa Waubonsee Community College Delores Tull Itawamba Community College Rober Turem an Paul D . Camp Community College Jane Turk LaSalle University Sylvia Unwin Bellevue Community College Stewart Venit California State University, Los Angeles David Walter Virginia State University Ju Wang Virginia State University Doug White University of Northern Colorado Chris Wild Old Dominion University Cat herine Wyman DeVry Institute of Technology, Phoenix Sherali Zeadally University of the District of Columbia Chaim Ziegler Brooklyn College

The authors would like to thank their students at Haywood Community College and North Central College for inspiring them to write student -friendly books . They would also like to thank their families for their tremendous support throughout this project. An especially big thanks goes to our terrific editorial, production, and marketing team at Pearson . In particular we want to thank our editor Matt Goldstein and our production program manager Carole Snyder, who have been instrumental in guiding the product ion of this book . We also want to thank our project manager, Rose Kernan, who helped everything run smooth ly, and our meticulous and knowledgable copyeditor, Shelly Gerger-Knechtl, who dedicated many hours to making this book the best book it could be. You are great people to work with !

xxix

xxx

Preface

About the Authors Tony Gaddis is the principal author of the Starting Out With series of textbooks. He is a highly acclaimed instructor with two decades of experience teaching computer science courses, primarily at Hayw ood Commun ity College. Tony was previously selected as the North Carolina Community College "Teacher of the Year" and has received the Teaching Excellence award from the National Institut e for Staff and Organizational Development. The Starting Out With series includes introductory textbooks covering Programming Logic and Design, C++, Java™, Microsoft® Visual Basic®, Microsoft® C#, Python, App Inventor, and Alice, all published by Pearson. Judy Walters is an Associate Professor of Computer Science at North Central College in Naperville, Illinois, where she teaches courses in both Computer Science and Media Studies. She is also very involved with Intern ationa l Programs at her college and has spent three semesters teaching in Costa Rica, where she hopes to retire some day. Godfrey Muganda is a Professor of Computer Science at North Central College. H e teaches a wide variety of courses at both the undergraduate and graduate levels, including courses in Algorithms, Computer Organization, Web Applications, and Web Services.

Credits Chapter 1

Figure 1-1: PowerPoint 2013, Windows 7, Microsoft Corporation Figure 1-2a: Digital webcam in a white background with reflection: Iko/Shutterstock Figure 1-2b: Modern flight joystick isolated on white background: Nikita Rogul/ Shutterstock Figure 1-2c: Scanner close up shot, business concept: Feng Yu/Shutterstock Figure 1-2d: Black Wireless Computer Keyboard and Mouse Isolated on White: Chiyacat/Shutterstock Figure 1-2e: Compact photo camera: Eikostas/Shutterstock Figure 1-2f: Computer drawing tablet with pen: Tkem ot/Shutterstock Figure 1-2g: Illustration of Hard disk drive HDD isolated on white background with soft shadow: Vitaly Korov in/Shutt erstock Figure 1-2h: Small computer speakers isolated on a white background: StockPhotosArt/Shutterstock Figure 1-2i: Color Print er: Jocic/Shutter stock Figure 1-2j: Four monitors. Vector: Art gallery/Shutterstock Figure 1-2k: Stick of computer random access memory (RAM): Peter Guess/Shutterstock Figure 1-21: Chip processor radiator: Aquila/Shutterstock Figure 1-7: Screenshot of Microsoft Visual Studio, Microsoft Corporation Chapter 2

Figure 2-1:

Screenshots of Microsoft DOS, Microsoft Corporation

Chapter 5

Figure 5-11: Windows 10, Microsoft Corporation Figure 5-12: Windows 10, Microsoft Corporation All other Figures and Tables by the Authors

PROGRAMMING PRACTICE W ith MyProgramminglab, your students will gain first-hand programming experience in an interactive online environment.

IMMEDIATE, PERSONALIZED FEEDBACK MyProgramminglab automa tically detec ts errors in the logic and syntax of their code subm ission and offers targeted hints that enables students to figure out what wen t wrong and why. MyProgramming lab ·

GRADUATED COMPLEXITY

.,

COOfl All ANAi YSIS • COMl'II fR 11:UIOR(S)

Rem.-,1(..-:

MyProgramminglab breaks down programming concepts into short , understandab le sequences of exercises. With in each sequence the leve l and sophist ication of the exercises increase gradually but stead ily.

• ~ll

Vo,.,.,_,.,,"""',....bt.clfflndwlt:)c~,C hours;

II Get the hourly

pay rate. cout > rate;

;

16

17 18

II Calculate pay=

the pay. hours* rate;

19

20 21 22

II Di splay the pay . cout '°"wc,rlct * :

lt 1l

p

s.9"'.. B

(



Qutd.l..uodl(Clll•Q)

?•

(GI""' S 3 us i ng namespace std; 4

5 i nt mai n() 6 {

7 8

cout >

us e r enter the numerator "Ente r the numerator: "; numerator; "Ente r the denominator: "; denomi nator;

value

of a fract i on . \n";

and deno minator

16

17 18 19 20 )

// Compute and disp l ay the dec i mal value cout heig ht; cout num3;

16

avg = num1 + num2 + num3 I 3· '

17

cout >

num2;

14

cout

number1 >> number2;

multiply\n";

product= number1 * number2; cout = y);

z is assigned 1 because xis greater than or equal to y.

cout = 0 G) X = x. C) x >= y is the same as y y and it is also true that x < z, does that mean y < z is true? B) If it is true that x >= y and it is also true that z == x, does that mean that z == y is true? C) If it is true that x ! = y and it is also true that x ! = z , does that mean that z ! = y is true?

4.4

What will the following program segment display? i nt a=

0, b = 2 , x = 4, y = O;

cout 12 )) cout 12 is evaluated to produce a true or false result. Th en, finally, these two results are ANDed together to arr ive at a final result for the entire expression. Th e cout statement will only be executed if temperature is less than 20 AND minut es is greater than 12. If either relationa l test is false, the entire expression is false and the cout statement is not executed . Table 4- 7 shows a truth table for the && operator. Th e truth table lists all the possible comb inations of values that two express ions may have and the resulting value returned by the && operator connecting the two expressions . As the table shows, both sub expressions must be true for the && operator to return a true value.

189

190

Chapte r 4

Making Decisions

Table 4 - 7 Logical AND Expression

Value of th e Expression

false

&&fa ls e

false

(0)

false

&&true

false

(0)

true

&&fa ls e

false

(0)

true

&&true

true

( 1)

0

NOTE: If the su bexpression on the left side of an && operator is false, the express ion on the right side will not be chec ked . Because the entire express ion is false if even just one of the su bexpressions is false, it would waste CPU time to check the remaining express ion . Thi s is ca lled short -circuit evaluation .

Th e &&operator can be used to simplify programs that othe rwi se wou ld use nested i f statements . Program 4 -12 is similar to Program 4 -11, wh ich determines if a bank customer qua lifies for a specia l interest rate . H owever, Program 4 -12 uses the logica l &&operator instead of nested i f statements.

Program 4 - 12 1 2

II Thi s program determ i nes whether a loan app licant qualifies for II a spec ia l loan i nteres t rate. It uses the &&logical operator.

3 #include 4 using namespace std ; 5

6 int 7 { 8 9

mai n () char

employed, rece nt Grad;

II Currently employed? (Y or N) II Recent college graduate? (Y or

N)

10 11

12 13

II Is the applicant

employed and a recent college cout

"Are you employed? ". ' employed; "Have you graduated from college recen t Grad;

in t he past

two years?

".

(program continues)

4.7 Logical Operato rs

(continued)

Program 4-12

20 21 22 23

Determine if (employed cout = MIN_ INCOMEI I years> MIN_YEARS ) II Uses lo gical cout > months ;

II Set charges

33

switch

34

{

36 37 38

39 40

based on user i nput

(choice)

case 1: charges break; case 2: charges break; case 3: charges

35

}

..'

= months

*

ADULT _RATE;

= months

*

CHILO _RATE;

= months

*

SENIDR _ RATE; (program continues)

2 19

2 20

Chap ter 4

Making Decisions

Program 4-27

(continued)

41 42 43 44 45 46 47

// Di splay the monthly charges cout > delivered ;

'y')) delivered?

(Y/ N):

";

) Calculate costs i f (h eight < 3) treeCost = PRICE_ 1; else if(height next

= new Li stNode (number );

Putting all of this together, we get the add function shown in lines 7- 23 of Numberl i st . cpp.

Displaying a List Th e code for the di spl ayl i st member function, in lines 29- 39, is based on the algorithm for traversing a list presented in the last section .

Destroying the List It is important for the class's destructor to release all the memory used by the list. It

does this by stepping through the list, deleting one node at a time. The code for doing so is found in lines 44- 56 of the Numberl i st. cpp file. A pointer nodePtr starts at the beginning (head) of the list and steps through the list one node at a time. A second pointer , garbage , follows in nodePtr ' s wake and is used to delete each node as soon as nodePt r has passed on to the node 's successor. Program 17-3 demonstrates the operation of the member functions of the Numberl i st class. Program 17- 3 1 2 3 4 5 6 7

II II

Thi s program demonstrates the display linked list operations.

add and

#include "Numberlist.h" using names pace std ; int

main()

8 {

Numberlist 1 i st; 1 ist.add(2.5); 1 i st. add ( 7 . 9 ) ; list.add( 12 . 6 ); list.d i splayl i st(); cout next = nodePtr - >next; delete nodePtr;

} }

87 }

88 89 //***************************************************

90 II displayList outputs a sequence of all 91 II currently stored in the list.

values

* *

92 //***************************************************

93 template 94 void Li nkedLi st: :d i splayList(} const 95 { ListNode *nodePtr = head ; II Start 96 97 while (nodePtr} 98

{

II Print

99

the value i n the current node ". cout value number ) { II Create a node to hold th i s number numberLi st = new Li stNode (numbe r, numberList); } II Print the list cout next = nullptr;

I I Fix the tai 1 II al is t now poi nt s to t he head

Th e tail is shorte r than the original input list and is therefore closer to the base case. Using recurs ion, the funct ion adds the value to the tail of the list, resulting in a "b igger" tail: listNode

*biggerTail

= add(tail

, value);

Finally , the or iginal head , which is being pointed to by al i st , is reattached to the bigger tail , and a pointer to the original head is returned: ali st - >next = big gerTail; return alist ;

II II

Reattach the head Ret urn pointer to augmented list

1063

1064

Chapte r 17

Lin ked Lists

Puttin g all of this together, we get the following code for the add function : 42 Numberlist2 : :ListNode *Numberlist2: :add (Li stNode *alist, 43 { 44 if (alist == nullptr) 45 return new ListNode (valu e ); 46 else 47

{

II Split into constituent head and tail ListNode *tai l= aList -> next; II tail II Detached head alist ->ne xt = nul l pt r; II Recursively add value to tail ListNode *big gerTail = add (ta i l, value); II Reattach the head alist ->ne xt = biggerTail ; II Return pointer to head of bigger list return aList;

48 49 50 51 52 53 54 55 56 57

doubl e value)

)

58 } Th e code in this function can be shortened . First, notice that line 50 is not needed. Th e head does not have to be detached before making the recursive call on the tail in line 52, as long as it is "reattached" in line 54. Th en, we can eliminate the tail var iable and just use al i st->next in line 52. Th e code in the else clause then gets sho rtened to ListNode *biggerTail = add(aList - >next , value); aLi st - >next = biggerTail; return alist ; which can in tum be shortened to aLi st - >next = add(alist return alist;

-> next , value);

Th e add function can therefore be written as follows: 28 NumberList2 : :ListNode *NumberList2: :add (Li stNode *alist, 29 { 30 if (aLis t == nullptr) 31 return new ListNode (valu e ); 32 else 33 { II Add the value to the end of the tail 34 35 aList ->ne xt = add(aL is t - >next, value); 36 return aList; 37

doubl e value)

}

38 }

The Recursive remove Member Function Th e remove function ListNode *remove(ListNode

*alist,

doubl e value)

takes as paramete r an inp ut list and a value, removes the value from the input list, and returns the resulti ng list. If the val ue to be removed is not on the list, the function returns the input list unchanged .

17.4 Recursive Linked List Operations

The function works as follows . If the list is empty, the function returns nul 1 ptr . i f(alis

t

==nullptr)

return

nullptr;

Otherwise, the function compares the value to what is stored in the first (head) node of the list . If the value is found there, the head node (pointed to by al i st) is deleted and the function returns the tail: i f (al i st - >value

==value)

{

Li stNode *t a i l = aLis t- >next; dele t e aList; re t ur n tail; }

The last case considered is when the list is not empty and the head of the list does not contain the va lue to be removed. In this case, the function recursively removes the value from the tail of the list, reattaches the original head to the modified tai l, and returns a pointer to the head of the (possibly) modified list . Using the same reasoning as in the add ( ) function, we can write this case as a Li st - >next = remove(aL i st - >next, return alis t ;

value};

Again putting it all together, we get the complete function as found lines 10- 60 of the implementation file Numberl i s t 2 . cpp . Contents of NumberLi st2. cpp 1 #include "NumberList2. h " 2 3 //******************************************* 4 II Ret urns the number of elemen t s i n a lis t * 5 II ******************************************

6 i nt NumberLi st2: :size(ListNode 7 {

8

if

9

10

*aList)

const

(alis t ==nullptr) retur n O;

else retur n 1 + size(aL i st - >next);

11

12 } 13 14 //*******************************************

15 II

Prints

all

elemen t s stored

in a list

*

16 //*******************************************

17 void NumberLis t 2: :display Li st(Lis t Node *aLis t ) const 18 { 19 if (alis t != nullptr) 20 { 21 cout value number ; l i st.add(number); cout right ); } }

voi d IntBinaryTree

:: di splayPreOrder

(TreeNode *tr ee } const

{

if

(tree)

{

cout value right,

num);

29 }

30 31 //***************************************************

32 II destroySubTree is called by the destructor 33 II deletes all nodes i n the tree.

. It

* *

34 //***************************************************

35 void IntBinaryTree:

:destroySubtree(TreeNode

*tree)

36 {

37 38 39 40 41 42 }

i f (! tree } return ; destroySubtree (tre e->left); destroySubtree (tre e->right }; II Delete the node at the root delete tree;

43 44 //***************************************************

45 II searchNode determines i f a value i s present 46 II the tree . If so, the function returns true. 47 II Otherwise, it returns false. 48 //***************************************************

49 bool IntBinaryTree:

:search(int

num) const

50 {

51 52 53 54 55 56 57 58 59 60 61 62

TreeNode *tree=

root;

while (t ree ) { i f (t ree->value == num} return true; else if (num < tree -> value} tree= tree - >left; else tree= tree - >r ight ; } return false;

63 }

64 65 //********************************************

66 II remove deletes the node in the given tree* 67 II that has a value member the same as num. * 68 //********************************************

in

* * *

19.2 Binary Search Tree Operations

69 void IntBina ry Tree : :remove(TreeNode *&tree , int 70 { 71 if (tr ee == nullptr) return; 72 if (num < tree - >value) 73 remove(tree - >left, num); 74 else if ( num > tree - >value) 75 remove(tree - >right,num); 76 else 77 II We have found the node to delete 78 makeDeletion (tree ); 79 } 80

num)

81 //***********************************************************

82 83 84 85 86 87 88

// // // // // // //

makeDeletion takes a reference to a tree whose root is to be deleted. If the tree has a single child, the tree is rep l aced by the single ch ild after the removal of it s root node . If the tree has two ch i l dren the le ft subtree of the de l eted node is attached at an appropriate point in the right subtree, and then the r ight subtree replaces the or igi nal tree.

89 //***********************************************************

90 void IntBina ry Tree : :makeDeletion(TreeNode *&tree ) 91 { 92 // Used to hold node that will be deleted 93 TreeNode *nodeToDelete = tree ; 94 95 // Used to locate the point where the 96 // left subtree is attached 97 TreeNode *attachPoint ; 98 99 if (tr ee - >r i ght == nullptr) 100 { 101 // Replace tree with its l eft subtree 102 tree= tree - >left; 103 } 104 else if (t ree-> l eft == nullptr) 105 { 106 // Replace tree with its right subtree 107 tree= tree - >right; 108 } 109 else 110 // The node has two children 111 { 112 // Move to right subtree 113 attachPoint = tree - >right; 114 115 II Locate the smallest node i n the right subtree 116 // by moving as far to the left as possible 117 whil e (attachPoint - >left != nullptr) 118 attachPoint = attachPoint - >left; 119 // Attach the le ft subtree of the original tree 120 II as the l eft subtree of the smallest node 121

• • • • • • •

1143

1144

Chapte r 19

Binary Trees 122 123 124 125 126 127 128 129 130 131 } 132

// in the right subtree attachPoint - >left = tree - >left; // Replace the or i ginal tree= tree - >right;

tree

with its

right

subtree

}

// Delete root of or igi nal tree delete nodeToDelete ;

133 //*********************************************************

134 // This function 135 / / in i norder .

displays

the values

stored

in a tree

* *

136 //*********************************************************

137 void 138 { 139 if 140 { 141 142 143 144 } 145 } 146

IntBinaryTree:

:d i splaylnOrder(TreeNode

*tree)

const

(tree} displaylnOrder (tre e->left); cout value right}



;

147 //*********************************************************

148 // This function 149 / / in i norder .

displays

the values

stored

in a tree

*

*

150 //*********************************************************

151 void 152 { 153 if 154 { 155 156 157 158 } 159 } 160

IntBinaryTree:

:d i splayPreOrder(TreeNode

*tree)

const

(tree} cout value 0) out

? @

1155

1156

Appendix A

The ASCII Characte r Set

Dec

Printab le ASCII Characters Hex Oct Character

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78

101 102 103 104 105 106 107 110 111 112 113 114 115 116 117 120 121 122 123 124 125 126 127 130 131 132 133 134 135 136 137 140 141 142 143 144 145 146 147 150 151 152 153 154 155 156 157 160 161 162 163 164 165 166 167 170

A B C D E F G H

Dec

Printab le ASCII Characters Hex Oct Character

121 122 123 124 125 126

79 7a 7b 7c 7d 7e

Dec

Extended ASCII Characte rs Hex Oct Character

171 172 173 174 175 176

y

z {

I }

I J K L M N

0 p Q

R

s T

u V

w X

y

z [ \

l

" -. a b C

d e f g h i j k l m

n 0

p q

r s

t u V

w X

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

80 81 82 83 84 85 86 87 88 89

Ba 8b

Be 8d

Be 8f 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f aO a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab

200 201 202 203 204 205 206 207 210 211 212 213 214 215 216 217 220 221 222 223 224 225 226 227 230 231 232 233 234 235 236 237 240 241 242 243 244 245 246 247 250 251 252 253

> r .width; cout =), 156- 157 greater than relational operator(>), 156 greatest common divisor (gcd) function, 924-925 greedy strategy, 937 Green Fields Landscaping case study, 138- 141, 227- 231

H . h files, 446 hand tracing a program, 136- 138 hand le creation, 486 hand ling exceptions. See exceptions hardware components, 3 CPU, 3-4 input devices, 6 main memory, 5 output devices, 6 secondary storage, 5-6 has-a relationship , 776, 781 header files algor ith m,931, 1003 brackets (< >) for, 28, 30, 449,564 cctype, 207- 208 cmath, 89, 130 cstd l i b, 133,383 cst r i ng, 820 ct i me, 134- 135 current project directory(" "), 449 defined, 28 fst r eam, 289, 853-855 . h, 446 ifstream,289 - 290,853 - 855 #inc 1 ude directive, 36 include guard for, 447 iomani p, 108, 110 i ostream, 28, 29, 36, 77, 80 ofstream, 289, 290-293, 853- 855 preprocessor directives and, 28,449 st r i ng, 56,411 vector, 564 heap, 671 hexadecima l integer literals, 47

hierarchica l (layered) function calls, 330-331 hierarchy chart, 19- 20 High Adventure Travel Agency case study, 391 high-level programming language, 9- 11 high-order bit, 98 Home Software Company case study, 469-475

I 1/0 (input/output) See also input; output manipulators, 33- 34, 108- 116 1/0 stream. See also files 1/0 stream member functions get, 869- 871 get 1 i ne, 866-869 peek, 871- 873 put, 873 IDE (integrated development environment), 12- 13 identifier defined, 41 legal names, 42 if statement conditional execution of, 161- 164 defined, 161 flowchart, 161- 162 format, 162 if /e l se statement versus, 171- 173 nested, 185- 188 programming style and, 164-165 if/e l se statement defined, 170 flowchart, 170 format, 170 if statement versus, 171- 173 nested, 185- 188 if/e l se if statement, 175- 181 defined, 175 flowchart, 176 format, 176 trai ling el se, 180-181 #ifndef directive, 44 7 i fstream class, 289 - 290, 853- 855 image maps, 1074-1080 implementation file, class (. cpp), 446, 447-449 #inc 1 ude directive, 28, 36 in multi-fileprograms, 446-449 include file director y( < >), 449 include guard, 44 7 increment operator(++) defined, 253 in mathematical expressions, 256- 257

num++contro l variab le, 253, 255 - 256 pointers using, 656 prefix/postfix modes, 25 4- 256 in relationa l expressions, 257 indirect recursion, 921 indirection operator(•), 647-650, 663,680-681 infinite loops, 246- 247 infix expressions, 941- 944 converting postfix to, 1117- 1119 inheritance base class 782- 784, 787, 790-791, 794-796,953-955 base class access specification, 784, 787, 790-791 class temp lates and, 1012- 1015 composition versus, 969- 973 constructors and, 792- 796 defined for OOP, 782 derived class, 782- 784 desrructors and , 792- 794 genera lization and specialization of, 782 hierarchies of, 949- 950 is-a relationship, 782- 784 multip le, 787 passing arguments to constructors, 794- 796 pointers , 785- 786, 953-955 private members, 783- 784, 790 protecte d members, 787- 790 public members, 783- 784, 790 superclasses and subclasses, 787 type compatibility in, 949- 955 virtua l functions, 957- 960, 963 initialization arra y, 518- 524 assignment versus, 730- 731 brace notation ( { }) for, 524 constructors, with, 423 -4 24, 457-458 copy constructors, with, 721- 722 defined, 59 globa l variab les set to zero, 357 loca l variab le, 356 member lists, with, 776- 778 named constants, with, 100 object, 423-424, 456-458 partial arra y, 522 - 523 pointer , 656-658 structure, 456-458 two -dimensiona l (2DJ arra y,

555- 556 variab le, 60-61 vector, 564-565 initialization expression, See for loop initialization list, 456-457

Index initialization value, 100 inline member function, 417, 422 inner loop, See loops inorder traversal, See binary search trees input characters, 119 console, 77 defined, 17 devices, 6 entering multiple values, 80-83 keyboard buffer, 79- 82 program data, 17 reading data, 77- 80, 129, 513- 514 rest data, 21 validation, See input validation input file, 286 input/output (1/0). See I/0 (input/output ) input-output stream library, 36 input stream , 851 input validation defined, 198 while loop, with, 250-252 i nputFil e object, 290, 294 instance of a class, 414 members, 704, 711 instantiating a class, 414 int. See data types; integer data types integer data types, 43-48 literals, 39, 46-47 size, 44 values, 29, 43-48 variables, 38, 45 integer division, 63, 95 integrated development environment (IDE), 12- 13 iomanip header file, 108, 110 ios class, 856, 874 iostream header file, 28, 29, 36, 77, 80 is-a relationship, 782- 784 i st r i ngstream class, 829- 830, 853 iteration. See also loops defined, 244 recursion versus, 940 stopping, 274, 281- 284 iterators. See also Standard Temp late Library (STL) begin() , 1018- 1019 defined, 1016 end(), 1018- 1019 pointer -like behavior , 1017, 1018 types, 1017 use of, 1018- 1019 vector use of, 763

J

. j pg extension, 288 justified output, 103- 109, 114-115

K key field, 610 key words C++ list of, 41 keyboard (input ) buffer, 79- 82

L lambda expressions, 761, 769- 770 last-in-first-out (LIFO ) structure, 1085- 1086 leaf node, 1125 left-to-right associativity, 87, 156 less than or equa l to relationa l operator() for, 680-681, 684 successor, 1038 t hi s, 703- 706 to char, 816, 819- 820 to a class object, 681-684 to a constant, 665-668 to a structure, 681- 684, 685 type casr assignment of, 950-953 type casting, 953- 955 unique, 686, 689 variables, 646, 648- 650 polymorphism, 955- 962 composition verws inheritance, 969- 973 defined, 955 dynamic binding and, 965 po lymorphic behavior, 955- 957 static binding and , 960 virtua l functions and , 955- 962 post -resr loops, 266 postfix expressions, 941- 944 converting ro infix, 1117- 1119 postorder tree traversa l, 1133- 1135 powfunction, 88- 90, 131- 132, 333,343

precedence associativity and , 1159 arithmetic operators, 85- 86 logical operators, 196- 197 relational operators, 159- 160 precision of floating-point data , 109 predicates, 762- 763 prefix expressions, 941- 944 prefix notation , 96 prefix/postfix operators(++) modes, 254- 256 overloading, 742- 743 preorder traversa l, 1133- 1135 preprocessor, 12 preprocessor directives #defi ne, 447 defined, 11 #endif, 447 #ifndef, 447 #inc l ude, 15, 28, 36, 446-450 pretest loops, 246,271,274 pr iv ate class members access specification, 783- 784 base class versus derived class, 790 class functions, 432-434 class variab les, 469 placement of, 413 prob lem domain, 479 procedural programming, 409. See also programming processing program data, 17 program language elements, 13- 15 parts of, 8- 13 statements, 15- 16, 69 variab les, 16-17 program -defined data types, 563-564 programmer, 2 programming. See also programming style; program modular , 323-324 object-oriented (OOP), 409 -4 11, 469-475 procedural, 409 process, 18-23 programming languages, 8- 11, 13- 15 BASIC, 10 C, 10 C++, 8- 9, 10 C#, 10 COBOL, 10 defined, 8 elements of, 13- 15 FORTRAN, 10 high-level, 9 Java, 10

JavaScript, 10 key words, 14- 15 low level, 9 Pascal, 10 Python, 10 Ruby, 11 Visual Basic, 11 programming style C++, 67-69 code alignment and indentation, 68, 187- 188 defined, 67 if statements, 164-165 while loops,248 - 249 promoted data type conversion, 93 prompt, 78 protected class members, 787- 790 prototype. See function prototype pseudocode, 20 pseudorandom numbers, 133 pub1 i c class members access specification, 783- 784 accessing, 415-416 base class versus derived class, 790 class variab le examp les, 470 dot operator (.) for, 415 placement of, 413 punctuation, 15 pure virtual functions, 963- 965 Pythagorean theorem, 131

Q quadratic time, 634 queue container, STL, 1109, 1111- 1112 queues, 1099- 1116 abstract data type (ADT), 1099- 1106 application of, 1099 circular arrays for, 1102 defined, 1099 deque container, 1109- 1111 dequeue operations, 1099- 1101 dynamic, 1099, 1106- 1109 empty, 1102 enqueue operations, 1099- 1101 first-in-first-our (FIFO) order, 1099 front/rear pointers , 1100-1101, 1106 full, 1102 linked lisr Implementation, 1099, 1106 operations, 1099- 1102 overflow exceptions, 1105- 1106 queue container, 1109, 1111- 1112

1233

123 4

Index queues (continued) Standard Template Library (STL), 1109- 1112 static, 1099, 1103- 1106 underflow exceptions, 1105- 1106 value adjustment operator {%), 1102 Quicksort algorithm, 634, 929- 933, 1112- 1116

R \r (return escape sequence), 35 RAM (random-access memory), 5, 16 ran d() function, 133, 135- 136 random access files, 866- 893 defined, 886 file positioning flags, 887- 888 1/0 (input/output ), 886- 893 mode flags, 887- 888 seekp and seekg member functions, 887- 891 sequential access files versus, 886- 887 tellp and te ll g member functions, 891- 893 random -access memory (RAM), 5, 16 random numbers, 132- 136 limiting range of, 135- 136 pseudorandom numbers, 133 seed value, 133- 135 range-based for loop, 525- 528, 567 raw pointer, 687. See also pointers rea d member function, 880 reading data binary files, 880-881 c i n object for, 77- 83 defined, 286-287 files, 286- 287, 294-297 from a file into arrays, 513- 514 input file, 286 i nputFil e object, 290, 294 member functions for, 865- 873 multip le values, 80- 83 program input, 77- 83 read position, 29 5- 296 stream extraction operator(») for, 78- 79, 294 user-specified filename for, 296- 297 records creating using structures, 881- 882 defined, 868 end of (\n), 869 fields in, 868, 881- 882

recursion, 915- 948 binary search algorithm using, 927- 928 depth of, 916 direct, 921 eliminating, 1112- 1116 enumeration algorithm using, 936- 940 exhaustive algorithm using, 936- 940 Fibonacci numbers problem, 925- 926 functions for, 915- 925, 927- 933 indirect, 921 iteration versus, 940 linked list operations, 1059- 1060 prob lem solution using, 919- 921, 925- 926,933 - 940 QuickSort algorit hm and, 929- 933, 1112- 1116 Towers of Hanoi prob lem, 933- 936 recursive functions add(), 1063-1064 base case, 918, 920 binary search algorithm, 927- 928 calling process, 915- 921 defined, 915 factorial, 922- 924 gcd (greatest common divisor), 924- 925 linked lists, 1060-1067 list members, 1062- 1067 QuickSort algorit hm, 929- 933 remove(), 1064- 1067 recursive implementation, 1132 reference count, 686 reference parameters, 438-4 38, 726, 728,732 reference values, 60, 751- 753 reference variables ampersand(&) for, 368- 369, 527- 528 array range modification to, 527- 528 comparing to passing by value, 372- 373 defined, 368 function parameters as, 368- 3 72 passing arguments by reference, 368- 376 passing files to functions, 374- 376 pointers, 370 prototype for, 368-369 reinterpret

_cast expression,

879- 880 relationa l expression, 156-160

relational operators, 155- 158 associativity, 156 comparing characters using, 203- 205 comparing strings using, 205- 207 defined, 155 overloading, 738- 741 precedence of, 159- 160 Reliable Software Systems, Inc., case study, 1071- 1074 remainder, 63 rethrowing exceptions, 998- 999 ret urn statements

defined, 342 function ending process, 342- 343 multiple values from functions,

344 objects from functions, 439-441 value-returning functions, 343- 351 rewinding files, 873- 875 right-justified output, 103-109 right stream manipulator, 114- 116, 859 root, binary trees, 1125, 1131, 1132 roun d function, 131 round -off error, 173- 174 running total, 260-262 accumulator, 260-261 defined, 260 flowchart, 261 run-time error, 21, 1049 run-time library, 11, 130- 132 rvalue, 60, 751- 753

s manipulator, 859,860 scientific notation, 48 scope of a variable, 61-62, 200-203 scope resolution operator (: : ), 41 7 screen contro l cell coordinates, 487 clearing the sere.en, 354 cursor position, 486-489 hand le creation, 486 input form creation, 489-491 search algorithms. See also algorithms; binary search trees array of objects or structures, 610-612 binary, 606-609, 634 defined, 603 linear (sequential), 603-606, 634 search key, 610 vectors, 624-626 search key, 610 search values, nodes, 1128 scie ntific

Index secondary storage, 5-6 Secure Encryption Systems, Inc. case study, 973-976 seed, 133- 135 selection sort, 617- 621, 634 self-documenting programs, 223 sentinel values, 263- 264 sequentia l access files, 287. See also binary files; 1/0 streams; text files sequentia l containers, 564, 1016. See also containers serialization of objects, 899. See also object serialization set container, 1017 set functions (mutators), 416,419 Set Intersection case study, 5 87 shared pointers, 686, 692- 693 shared_ptr class doub le dipping danger, 693 dynamic memory allocation using, 691-694 make_share d() function, 693-694 member functions, 694 vector types in, 694 short -circuit evaluation, 190, 193 shor t i nt. See data types; integer data types significant digits, 109 single-line comments (i /), 28, 66 single-precision data types, 49 size declarator ( 11), 124- 125, 508- 510 size() member function, 569- 570, 1097 si zeof operator, 44, 58-59 slash misuse, forward ( /) versus back (1), 35 smart pointers, 686-694 choosing between raw and, 1070 contro l blocks, 691-692 arrays and , 689 defined, 686 dynamic memory allocation ownership, 686-694 linked lists, 1070 shared pointers, 686, 692-693 shar ed_ptr class, 691-694 unique pointers, 686, 689 uniq ue_ptr class, 687-691 vector types and, 694 software app lication, 7 defined, 2 system, 6- 7 software developer, 2

software development abstraction in, 408 too ls, 7 software engineering, 22 sorting C-string lists, 826-827 function objects for arrays and vectors, 763 linked lists in order, 1048- 1049 ranges, 1112- 1113 stacks for, 1113- 1116 sorting algorithms. See also algorithms array of objects or structures, 621-624, 763 bubble sort, 613- 617, 634 defined, 613 pass, 614 Quicksort , 634, 929- 933, 1112- 1116 recursive functions for, 929- 933 selection sort, 617-621, 634 vectors, 624-626, 763 source code, 11- 12 writing and compiling, 21 space criterion, 62 7 special characters, 30 specification files, class, 446-447 spreadshe.ets, data storage of, 286 sq r t function, 131 stack container, sn, 1097- 1098 stacks, 1085- 1098 abstract data type (ADT), 1085- 1093 applications of, 1086 defined, 422, 1085 dynamic, 1086, 109 3- 1096 eliminating recursion, 1112- 1116 handling exceptions, 1091- 1093 IntStack class, 1087- 1091 i sEmptyfunction, 1087, 1093, 1095 last-in-first-out (LIFO) structure, 1085- 1086 linked list implementation, 1086, 1093- 1095 member functions, 1087, 1097 operations, 1086- 1086 overflow exception, 1088- 1089, 1092 pop and push member functions, 1087- 1089, 1092- 1093, 1095 Quicksort algorithm and , 1112- 1116 Standard Template Library (STI) , 1097- 1098 static, 1086- 1091 templates, 1093

underflow exception , 1088- 1089, 1092- 1093 stale data, 422 stand -alone operator overloading, 741- 742 Standard Template Library (STL) algorit hms, 1022- 1029 associative containers, 564, 1016-1017 containers, 564 , 1016-1017, 1020-1021, 1097- 1098 data types, 563- 564 deque container, 1109- 1111 iterators, 763, 1016, 1017- 1019 linked lists, 1068- 1070 1i st container, 1016, 1068- 1070 member functions, 1020- 1021, 1068- 1069, 1097, 1110 queue container, 1109, 1111- 1112 sequentia l containers, 564, 1016 stack container, 1097- 1098 vecto r container, 1020-1021 statements assignment, 59-61, 102- 105 br eak, 281 - 283 case, 213 - 214 cont in ue,283 - 284 double, 17 do-whil e loop, 265- 270 for loop, 271- 276 function calls, 325- 331 header expressions, 2 71- 2 72 if, 161- 169 if/else, 170- 174 if/else if, 175- 181 #i nclude, 21 length of, 69 mathematica l expressions converting to, 87- 90 multip le, 275- 276 programming, 15- 16, 69 repeating, 244 switch, 213-220 while loops,243 - 252 static binding, 960 stat i c_cast expression, 94- 97, 951 static classes IntQueue, 1103- 1106 IntStack, 1087- 1091 stat i c key word, 709 static local variables, 362- 363 static members defined, 708 functions, 711- 714, 1087 stack class, 1087 variab les, 709- 711, 1087 static queues, 1099, 1103- 1106 static stacks, 1086- 1091

1235

1236

Index std namespace, 28 STI. See Standard Template Library (STI) storage. See data file storage; files; memory strcat function, 820, 827 strcle n function, 820,827 strcmp function, 823- 827 strcpy function, 126, 822, 827, 835 stream extraction operator(») c in object, 78- 79, 117- 118 data flow to varia bles, 78- 79 defined, 78 numeric conversions, 829 parsing numeric output, 878 operator overloading, 743- 747 reading data using, 78- 79, 294 whitespace and, 117- 118 stream insertion operator(«) C++ use of, 29, 32 cout object, 29, 32, 79 data flow from varia bles, 79 defined, 32 formatting numbers, 878 numeric conversions, 829 of stream object, 290-291 operator overloading, 743- 747 writing data using, 32, 290- 291 stream manipulators descriptions of, 858-859 endl, 33-34 fixed, 112 formatting output using, 107- 116 1/0 streams and, 857- 860 1eft, 114-115 right, 114- 115 setprec isi on, 109- 112 setw, 107- 109, 127 showpoin t, 113- 114 stream objects c in, 77- 83 cout, 29, 31- 36 defined, 32 file, 288, 289 - 290, 297 string class C-string relationship to, 815- 816 C++ use of, 56-57, 839- 842 combined assignment operator (·= ), 123-124 concatenation operator (+), 123- 124 constructors, 840 creating stri ng objects, 411-412 header file, 56, 411 #inc 1 ude directive, 56, 411 member functions, 123- 124, 411-412, 841- 842 operators, 840

st r i ng objects c_strng function for, 297 class functions and, 123- 124 creating, 411-412 defining, 564- 565 member functions, 123-124, 411-412 numeric conversions, 829- 831 strings ASCII values, 205 backs lash (11) for litera l output, 35,290 binary files, 877- 879 blank spaces in, 123 character -by-character processing, 538- 539 character litera ls versus, 53- 55 class library functions for, 815 comparing, 205 - 207 concatenation operator (+ ), 123- 124 escape characters in, 35- 36 functions for, 116-129 inputting, 117- 119 literals, 39-4 0, 53- 55 null characters, 815- 816 null terminator (/0), 54, 538 nwnbers converted to, 40, 877-879 processing arrays of, 538- 539 quotation marks(· ") for, 29, 35,40 relational operators for comparison of, 205- 207 storage of objects, 538 writing Cstring hand ling functions for, 833- 839 st ruct key word, 453 structure pointer operator( - >), 680-681,684 structures accessing members, 454-456 arrays of, 581- 584 constructors, 457-458 data members, 454-458 declaration, 453-454 defined, 453 dereferencingpointers to, 684-685 fields in, 881- 882 initializing, 456-458 nested, 458 -4 60 passing to functions, 462-463, 682-684 pointers as members of, 684-685 pointers to, 681-685 records created with, 881- 885 returning from functions, 463-464 search algorithms for, 610-612 sorting algor ithms for, 621-624

varia ble display and comparison, 456 varia ble definition , 454 stubs, 385- 387 subclass, 787 subscripts, 509- 510 subtraction operator (- ), 62-63 subtrees, 1126 successor nodes, 1125 successor pointer, 1038 superclass, 787 swap function template, 1002- 1003 switch statement, 213 - 220 break statements, 214- 215 case statements, 213- 214 default section, 215 - 216 defined, 213 fall-through capability, 216-218 syntax, 14, 67- 68 syntax errors, 11 system software, 6-7

T It (horizonta l tab escape sequence), 35 r· get() member function, 694 tan function, 131 tel lp and tellg member functions, 891- 893 template prefix, 1000 templates binary search trees, 1145 class, 1007- 1015 function, 999- 1007 linked list, 1055- 1059 stack, 1093 ternary operators, 62 test data , 21, 301- 303 test expression defined, 2 71 for loop header use, 2 71- 2 72 loop termination using, 274 testing. See also debugging application frameworks, 974- 976 bit flags for, 861- 862 Boolean varia bles, 194- 195 characters, 207 - 208 creating good test data , 301 - 303 exceptions for, 987- 988 file open error, 299- 300 1/0 streams, 861- 864 member functions for, 862- 864 output validation, 225- 227 text cipher, 973 editor, 11 files, 287, 878 plain, 973

Index th is pointer, 703-706 three -dimensional (30) arrays, 560- 562. See also arrays throw point, 988 throw statement, 988 throwing exceptions dynamic memory allocation, 671 error hand ling, 988 newoperator for, 997 rethrowing, 998- 999 stack underflow/overthrow, 1088- 1089, 1092- 1093 tilde character(-), 429 time criterion, 627 time function, 134- 135 to_stri ng() function, 690-691 top member function, 1097 top -down design, 19 toupper function, 267- 268 Towers of Hanoi problem, 933- 936 traversing binary search trees, 1133- 1135 lists, 1041- 1043 trees. See binary trees; binary search trees true/false values binary search trees, 1135- 1136 if statement, 167- 169 relationa l operators, 156- 160 returning from a function, 349- 351 variables, 57- 58 whil eloops,244-245 truncated value, 51, 94 try block, 988-989, 998 try/catch construct, 988- 990 two-dimensional (20) arrays, 553- 559 defined, 553 initialization, 555- 556 passing to functions, 556-558 processing contents, 553- 555 subscript operator ( I]) , 553 summing columns of, 559 summing elements in, 558 summing rows of, 558- 559 type cast expressions assignment, 950-953 base class pointers, 950-955 C- and C++-style, 96- 97 data type conversion using, 94-97 defined, 94 derived class pointers, 950-953 functiona l notation, 96- 97 inheritance hierarch y compatibi lity, 949- 955

integer division, 95 prefix notation, 96 rei nterpret _cast, 879- 880 static _cast, 94- 97, 951 value demotion and promotion, 92- 96 type coercion, 93 type compatibi lity, 950- 953 type conversion operators, 770-772 type parameters, 999, 1005 typedef statement, 543 . txt extension, 288

u UML class diagram, 409,412 unary functions, 766- 767 unary operators, 62, 86 unary predicate, 762 uncaught exceptions, 990 underflow exception queues, 1105- 1106 stacks, 1088- 1089, 1092- 1093 underflow, 98- 99 unique pointers, 686, 689 uniq ue_ptr class array deallocation using, 689 dynamic memory allocation using, 687-691 member functions, 690-691 unsig ned i nt value, 44-45, 93 unsig ned long in t values, 44-45, 93 unsig ned short i nt value, 44-45 unwinding the stack, 997- 998 update expression defined, 272 for loop header use, 271 - 272, 274 multiple statements in, 275- 276 USB flash drive, 6 user interfaces, object-oriented programming, 410-411 user specifications counter loop control, 259- 260 errors from, 185, 198- 200 filename, 296 - 297 input validation , 185, 198- 200 loops, 259- 260 user-controlled for loops, 2 75 using namespace std statement, 28 utility programs, 7

V validation debugging, 225- 22 7 input, 185, 198- 200, 250- 252 menu-driven programs, 185 output, 225- 22 7

user specifications, 185, 198- 200 whi1e loops for, 250-252 value. See also true/false values; variables ASCII comparisons, 203- 205 assignment statements, 37- 38, 59-61 assignment to C-strings, 126 binary trees, 1126, 1128, 1132, 1135- 1136 Boolean, 57- 58, 195- 196, 349- 351 integers, 38, 43-48, 51 litera l assignment, 39-40 node storage, 1126, 1128, 1132 nullptr, 1038- 1039, 1049, 1126 numerical, 16-17 passing arguments by, 338- 340 reference, 60, 751- 753 root node, 1132 stored in function objects, 765- 766 truncated, 51, 94 vector storage and retrieval, 565- 566 value ranking, 92- 93 value-returning functions, 343- 351. See also return statements calling, 345- 348 defined, 343 defining, 344- 345 prototype, 345 variab le definition defined, 16- 17 enumerated data types, 465 forloops,274-275 initialization expressions, 274- 275 initialization, 60-61 integers, 38, 45 modification and, 274- 275 one statement for declaring and,465 semicolon (;) ending for, 46 structures, 454 variab les accumulator, 260-261 address, 646 assignment statements, 37- 38, 59-61, 103 auto key word declaration, 61 avoiding modification, 274 Boolean, 19 5- 196 counter, 258- 260, 271 cout object, 38 data types, 16- 17, 58- 59 defined, 16

1237

1238

Index variables (co11ti11ued ) display and comparison of, 456 enum,465-466 enumerated data types, 465 false values, 57- 58 floating-point data types, 48- 51 function-defined, 355- 363 globa l, 355, 356- 362 indirection operator(•), 647- 650 initialization, 59-61 , 274- 275 integer values, 38, 43-48, 51 literal value assignment, 39-4 0 local, 355- 356, 361- 363 logical operators and, 195- 196 loop contro l (num), 253 , 255- 256,259 memory location, 16 name identifiers, 41-42 numerical va lues, 16-17 object members, 409-410 pointer, 647-650 reference, 368- 376 same name given to, 202- 203, 361- 362 scope of, 61-62 , 200-203 selection of data types, 43-44 s i zeof operator, 58- 59 stack class members, 1087 static local, 362 - 363 static members, 709- 711 structures , 453-464 true values, 57- 58 values changed by assignment, 102- 103 vector container , sn, 1020-1021, 1097- 1098 vector member functions at(), 574 capacity(), 574 clear() , 572, 574 empty, 572- 573, 574 pop_back,570-571,574 push_back,567 - 569,574

resize , 574 reverse, 574 s i ze, 569- 570 summary, 574 swap, 574 vectors, 563- 574 angle brackets(< >) for, 564 arra y subscript operator ( [) ), 564,566 arra ys and, 563- 574 clearing, 572 defining, 564- 565 detecting empty, 572- 573 function operators for, 763- 765 header file, 564 initializing, 564-565 iterators for, 763 linked list advantages over, 1037- 1038 range-based fo r loop with, 567 removing elements from, 570-571 removing objects from, 764- 765 search algorithms for, 624-626 sequence container data type, 564 shared pointers to, 694 sorting algorithms for, 624-626 , 763 sorting elements in, 763 value storage and retrieval, 565- 566 virtua l functions abstract base classes and, 693-695 abstract, 963 defined, 955 dynamic binding, 960 inheritance of, 957- 960, 963 overriding, 961- 962 polymorphism and , 955- 962 pure, 963- 965 static binding, 960 voi d functions, 325

w weak pointers, 686 web browsers, data storage of, 286 whi 1 e loops. See also loops body, 244 condition expressions, 244- 245 counters, 258- 260 flowchart, 244 header, 244, 271 infinite loop causes, 246- 247 input validation using, 250-252 iteration, 246 pretest loop process, 246 programming style and, 248- 249 repeating statement or block, 244 situations for use of, 278 true/false conditions , 244-245 whitespace characters , 117- 119, 865 wi dt h function, 127- 128 with draw member function, 471 word processors, data storage of, 286 worst -case complexit y, 630-632 wr ite member function, 879- 880 writing Cstring hand ling functions, 833- 839 writing data arra y contents to files, 514 cout object for, 31- 36 defined, 286 escape sequences and , 34- 36, 291 , 292 files, 286, 290-293 member functions for, 865- 873 of stream header file objects for, 289 , 290-293 output file, 286 output Fi 1e object, 290-291 program input, 31- 36 stream insertion operator («) for, 32,290-291 writing function temp lates, 999- 1002

C++ Quick Reference

Commonly Used C++ Data Types Data Tvne Descrintion cha r int sho rt int short unsigned int unsigned lo ng int lo ng f l oat doub l e Forms of the

if

Character Integer Short integer Same as s hort int Unsigned integer Same as u n sig ned int Long integer Same as l ong int Single precision floating point double precision floating point

Some Commonly Used Library Functions Name Description (The following require the cmath header file) pow Raises a number to a power sqrt Returns square root of a number (The following require the cstdlib header file) rand Generates a pseudo-random number sra nd Sets seed value for random numbers (The following require the cc type header file) toupper Returns a character's uppercase equivalent tolower Returns a character's lowercase equivalent The

St atemen t

while

Loop

Simple if

Example:

Form:

Example:

if

i f (x < y)

whi l e (expression)

wh ile

{

{

(expression) s tatem en t;

x++;

if/else if (expression) s tatem en tl; else s tatem en t2;

s tatement s tatement

Example:

i f (x < y) cout