Starting out with C++. Early objects [Ninth edition] 9780134400242, 1292157275, 9781292157276, 0134400240

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

283 116 11MB

English Pages xxx, 1238 pages; 26 cm [1273] Year 2016;2017

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover......Page 1
Title Page......Page 4
Copyright Page......Page 5
Contents at a Glance......Page 6
Contents......Page 8
Preface......Page 16
Acknowledgments......Page 28
About the Authors......Page 31
Acknowledgments for the Global Edition......Page 32
1.1 Why Program?......Page 36
1.2 Computer Systems: Hardware and Software......Page 38
1.3 Programs and Programming Languages......Page 43
1.4 What Is a Program Made of?......Page 48
1.5 Input, Processing, and Output......Page 52
1.6 The Programming Process......Page 53
1.7 Tying It All Together: Hi! It’s Me......Page 58
2.1 The Parts of a C++ Program......Page 62
2.2 The cout Object......Page 66
2.3 The # include Directive......Page 71
2.4 Variables and the Assignment Statement......Page 72
2.5 Literals......Page 74
2.6 Identifiers......Page 76
2.7 Integer Data Types......Page 78
2.8 Floating-Point Data Types......Page 83
2.9 The char Data Type......Page 87
2.10 The C++ string Class......Page 91
2.11 The bool Data Type......Page 92
2.12 Determining the Size of a Data Type......Page 93
2.13 More on Variable Assignments and Initialization......Page 94
2.14 Scope......Page 96
2.15 Arithmetic Operators......Page 97
2.16 Comments......Page 101
2.17 Programming Style......Page 102
2.18 Tying It All Together: Smile!......Page 104
3.1 The cin Object......Page 112
3.2 Mathematical Expressions......Page 119
3.3 Data Type Conversion and Type Casting......Page 127
3.4 Overflow and Underflow......Page 133
3.5 Named Constants......Page 134
3.6 Multiple and Combined Assignment......Page 137
3.7 Formatting Output......Page 141
3.8 Working with Characters and Strings......Page 151
3.9 More Mathematical Library Functions......Page 165
3.10 Random Numbers......Page 167
3.11 Focus on Debugging: Hand Tracing a Program......Page 171
3.12 Green Fields Landscaping Case Study—Part 1......Page 173
3.13 Tying It All Together: Word Game......Page 176
4.1 Relational Operators......Page 190
4.2 The if Statement......Page 196
4.3 The if/else Statement......Page 205
4.4 The if/else if Statement......Page 210
4.5 Menu-Driven Programs......Page 218
4.6 Nested if Statements......Page 220
4.7 Logical Operators......Page 224
4.8 Validating User Input......Page 233
4.9 More about Blocks and Scope......Page 235
4.10 More about Characters and Strings......Page 238
4.11 The Conditional Operator......Page 244
4.12 The switch Statement......Page 248
4.13 Enumerated Data Types......Page 257
4.14 Focus on Testing and Debugging: Validating Output Results......Page 260
4.15 Green Fields Landscaping Case Study—Part 2......Page 262
4.16 Tying It All Together: Fortune Teller......Page 267
5.1 Introduction to Loops: The while Loop......Page 278
5.2 Using the while Loop for Input Validation......Page 285
5.3 The Increment and Decrement Operators......Page 288
5.4 Counters......Page 293
5.5 Keeping a Running Total......Page 295
5.6 Sentinels......Page 298
5.7 The do-while Loop......Page 300
5.8 The for Loop......Page 306
5.9 Focus on Software Engineering: Deciding Which Loop to Use......Page 312
5.10 Nested Loops......Page 314
5.11 Breaking Out of a Loop......Page 316
5.12 Using Files for Data Storage......Page 320
5.13 Focus on Testing and Debugging: Creating Good Test Data......Page 336
5.14 Central Mountain Credit Union Case Study......Page 339
5.15 Tying It All Together: What a Colorful World......Page 343
6.1 Modular Programming......Page 358
6.2 Defining and Calling Functions......Page 359
6.3 Function Prototypes......Page 367
6.4 Sending Data into a Function......Page 368
6.5 Passing Data by Value......Page 373
6.6 The return Statement......Page 377
6.7 Returning a Value from a Function......Page 378
6.8 Returning a Boolean Value......Page 384
6.9 Using Functions in a Menu-Driven Program......Page 386
6.10 Local and Global Variables......Page 390
6.11 Static Local Variables......Page 397
6.12 Default Arguments......Page 399
6.13 Using Reference Variables as Parameters......Page 403
6.14 Overloading Functions......Page 413
6.15 The exit() Function......Page 417
6.16 Stubs and Drivers......Page 420
6.17 Little Lotto Case Study......Page 422
6.18 Tying It All Together: Glowing Jack-o-lantern......Page 427
7.1 Abstract Data Types......Page 442
7.2 Object-Oriented Programming......Page 444
7.3 Introduction to Classes......Page 446
7.4 Creating and Using Objects......Page 449
7.5 Defining Member Functions......Page 451
7.6 Constructors......Page 458
7.7 Destructors......Page 464
7.8 Private Member Functions......Page 467
7.9 Passing Objects to Functions......Page 470
7.10 Object Composition......Page 477
7.11 Focus on Software Engineering: Separating Class Specification, Implementation, and Client Code......Page 481
7.12 Structures......Page 488
7.13 More about Enumerated Data Types......Page 500
7.14 Home Software Company OOP Case Study......Page 504
7.15 Introduction to Object-Oriented Analysis and Design......Page 511
7.16 Screen Control......Page 521
7.17 Tying It All Together: Yoyo Animation......Page 526
8.1 Arrays Hold Multiple Values......Page 542
8.2 Accessing Array Elements......Page 544
8.3 Inputting and Displaying Array Data......Page 546
8.4 Array Initialization......Page 553
8.5 The Range-Based for loop......Page 560
8.6 Processing Array Contents......Page 563
8.7 Using Parallel Arrays......Page 574
8.9 Arrays as Function Arguments......Page 578
8.10 Two-Dimensional Arrays......Page 588
8.11 Arrays with Three or More Dimensions......Page 595
8.12 Vectors......Page 598
8.13 Arrays of Objects......Page 610
8.14 National Commerce Bank Case Study......Page 620
8.15 Tying It All Together: Rock, Paper, Scissors......Page 622
9.1 Introduction to Search Algorithms......Page 638
9.2 Searching an Array of Objects......Page 645
9.3 Introduction to Sorting Algorithms......Page 648
9.4 Sorting an Array of Objects......Page 656
9.5 Sorting and Searching Vectors......Page 659
9.6 Introduction to Analysis of Algorithms......Page 662
9.8 Tying It All Together: Secret Messages......Page 670
10.1 Pointers and the Address Operator......Page 680
10.2 Pointer Variables......Page 682
10.3 The Relationship Between Arrays and Pointers......Page 686
10.4 Pointer Arithmetic......Page 690
10.5 Initializing Pointers......Page 691
10.6 Comparing Pointers......Page 694
10.7 Pointers as Function Parameters......Page 696
10.8 Pointers to Constants and Constant Pointers......Page 700
10.9 Focus on Software Engineering: Dynamic Memory Allocation......Page 705
10.10 Focus on Software Engineering: Returning Pointers from Functions......Page 709
10.11 Pointers to Class Objects and Structures......Page 715
10.12 Focus on Software Engineering: Selecting Members of Objects......Page 719
10.13 Smart Pointers......Page 721
10.14 Tying It All Together: Pardon Me, Do You Have the Time?......Page 729
11.1 The this Pointer and Constant Member Functions......Page 738
11.2 Static Members......Page 743
11.3 Friends of Classes......Page 750
11.4 Memberwise Assignment......Page 755
11.5 Copy Constructors......Page 756
11.6 Operator Overloading......Page 765
11.7 Rvalue References and Move Operations......Page 786
11.8 Function Objects and Lambda Expressions......Page 796
11.9 Type Conversion Operators......Page 805
11.10 Convert Constructors......Page 808
11.11 Aggregation and Composition......Page 811
11.12 Inheritance......Page 817
11.13 Protected Members and Class Access......Page 822
11.14 Constructors, Destructors, and Inheritance......Page 827
11.15 Overriding Base Class Functions......Page 832
11.16 Tying It All Together: Putting Data on the World Wide Web......Page 835
12.1 C-Strings......Page 850
12.2 Library Functions for Working with C-Strings......Page 855
12.3 Conversions Between Numbers and Strings......Page 864
12.4 Writing Your Own C-String Handling Functions......Page 868
12.5 More about the C++ string Class......Page 874
12.6 Advanced Software Enterprises Case Study......Page 877
12.7 Tying It All Together: Program Execution Environments......Page 879
13.1 Input and Output Streams......Page 888
13.2 More Detailed Error Testing......Page 896
13.3 Member Functions for Reading and Writing Files......Page 900
13.4 Binary Files......Page 912
13.5 Creating Records with Structures......Page 916
13.6 Random-Access Files......Page 921
13.7 Opening a File for Both Input and Output......Page 928
13.8 Online Friendship Connections Case Study: Object Serialization......Page 933
13.9 Tying It All Together: File Merging and Color-Coded HTML......Page 938
14.1 Introduction to Recursion......Page 950
14.2 The Recursive Factorial Function......Page 957
14.3 The Recursive gcd Function......Page 959
14.4 Solving Recursively Defined Problems......Page 960
14.5 A Recursive Binary Search Function......Page 962
14.6 Focus on Problem Solving and Program Design: The QuickSort Algorithm......Page 964
14.7 The Towers of Hanoi......Page 968
14.8 Focus on Problem Solving: Exhaustive and Enumeration Algorithms......Page 971
14.9 Focus on Software Engineering: Recursion versus Iteration......Page 975
14.10 Tying It All Together: Infix and Prefix Expressions......Page 976
15.1 Type Compatibility in Inheritance Hierarchies......Page 984
15.2 Polymorphism and Virtual Member Functions......Page 990
15.3 Abstract Base Classes and Pure Virtual Functions......Page 998
15.4 Focus on Object-Oriented Programming: Composition versus Inheritance......Page 1004
15.5 Secure Encryption Systems, Inc., Case Study......Page 1008
15.6 Tying It All Together: Let’s Move It......Page 1011
16.1 Exceptions......Page 1022
16.2 Function Templates......Page 1034
16.3 Class Templates......Page 1042
16.4 Class Templates and Inheritance......Page 1047
16.5 Introduction to the Standard Template Library......Page 1051
16.6 Tying It All Together: Word Transformers Game......Page 1064
17.1 Introduction to the Linked List ADT......Page 1072
17.2 Linked List Operations......Page 1078
17.3 A Linked List Template......Page 1090
17.4 Recursive Linked List Operations......Page 1094
17.5 Variations of the Linked List......Page 1102
17.6 The STL list Container......Page 1103
17.7 Reliable Software Systems, Inc., Case Study......Page 1106
17.8 Tying It All Together: More on Graphics and Animation......Page 1109
18.1 Introduction to the Stack ADT......Page 1120
18.2 Dynamic Stacks......Page 1128
18.3 The STL stack Container......Page 1132
18.4 Introduction to the Queue ADT......Page 1134
18.5 Dynamic Queues......Page 1141
18.6 The STL deque and queue Containers......Page 1144
18.7 Focus on Problem Solving and Program Design: Eliminating Recursion......Page 1147
18.8 Tying It All Together: Converting Postfix Expressions to Infix......Page 1152
19.1 Definition and Applications of Binary Trees......Page 1160
19.2 Binary Search Tree Operations......Page 1164
19.4 Tying It All Together: Genealogy Trees......Page 1180
Appendix A: The ASCII Character Set......Page 1190
Appendix B: Operator Precedence and Associativity......Page 1194
Appendix C: Answers to Checkpoints......Page 1196
Appendix D: Answers to Odd-Numbered Review Questions......Page 1236
A......Page 1256
B......Page 1257
C......Page 1258
E......Page 1260
F......Page 1261
G......Page 1262
I......Page 1263
L......Page 1264
N......Page 1265
O......Page 1266
P......Page 1267
Q......Page 1268
S......Page 1269
T......Page 1271
V......Page 1272
W......Page 1273
Recommend Papers

Starting out with C++. Early objects [Ninth edition]
 9780134400242, 1292157275, 9781292157276, 0134400240

  • 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

Global edition

Starting Out With C++ Early Objects ninTH edition

Tony Gaddis • Judy Walters • Godfrey Muganda

LOCATION OF VIDEONOTES IN THE TEXT Chapter 1

VideoNote

Designing a Program with Pseudocode, p. 54 Designing the Account Balance Program, p. 59 Predicting the Output of Problem 30, p. 59 Solving the Candy Bar Sales Problem, p. 60

Chapter 2 Using cout to Display Output, p. 66 Assignment Statements, p. 93 Arithmetic Operators, p. 96 Solving the Restaurant Bill Problem, p. 108 Chapter 3

Using cin to Read Input, p. 111 Evaluating Mathematical Expressions, p. 118 Combined Assignment Operators, p. 136 Solving the Stadium Seating Problem, p. 182

Chapter 4

Using an if Statement, p. 195 Using an if/else Statement, p. 204 Using an if/else if Statement, p. 210 Using Logical Operators, p. 223 Solving the Time Calculator Problem, p. 272

Chapter 5 The while Loop, p. 278 The for Loop, p. 305 Nested Loops, p. 313 Solving the Ocean Levels Problem, p. 351 Chapter 6

Defining and Calling Functions, p. 358 Using Function Arguments, p. 367 Value-Returning Functions, p. 377 Solving the Markup Problem, p. 433

Chapter 7

Creating a Class, p. 446 Creating and Using Class Objects, p. 448 Creating and Using Structures, p. 488 Solving the Car Class Problem, p. 534

Chapter 8

Accessing Array Elements, p. 543 Passing an Array to a Function, p. 577 Two-Dimensional Arrays, p. 587 Solving the Chips and Salsa Problem, p. 627

Chapter 9

Performing a Binary Search, p. 640 Sorting a Set of Data, p. 647 Solving the Lottery Winners Problem, p. 675 (continued on next page)

LOCATION OF VIDEONOTES IN THE TEXT (continued) Chapter 10

Pointer Variables, p. 681 Dynamically Allocating an Array, p. 705 Solving the Days in Current Month Problem, p. 736

Chapter 11

Operator Overloading, p. 764 Aggregation and Composition, p. 810 Overriding Base Class Functions, p. 831 Solving the Number of Days Worked Problem, p. 845

Chapter 12

Converting Strings to Numbers, p. 863 Writing a C-String Handling Function, p. 867 Solving the Case Manipulator Problem, p. 884

Chapter 13

The get Family of Member Functions, p. 903 Rewinding a File, p. 907 Solving the File Encryption Filter Problem, p. 946

Chapter 14

Recursive Binary Search, p. 961 QuickSort, p. 963 Solving the Recursive Multiplication Problem, p. 981

Chapter 15

Polymorphism, p. 989 Composition versus Inheritance, p. 1003 Solving the Sequence Sum Problem, p. 1019

Chapter 16

Throwing and Handling Exceptions, p. 1022 Writing a Function Template, p. 1034 Iterators, p. 1051 Solving the Arithmetic Exceptions Problem, p. 1068

Chapter 17

Adding an Element to a Linked List, p. 1079 Removing an Element from a Linked List, p. 1086 Solving the Member Insertion by Position Problem, p. 1117

Chapter 18

Storing Objects in an STL Stack, p. 1131 Storing Objects in an STL Queue, p. 1145 Solving the File Reverser Problem, p. 1157

Chapter 19

Inserting an Element into a Binary Tree, p. 1166 Removing an Element from a Binary Tree, p. 1170 Solving the Tree Size Problem, p. 1186

VideoNote

Ninth Edition

Starting Out with

C++ Early Objects Global Edition

Tony Gaddis Judy Walters Godfrey Muganda

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: Matt Goldstein Editorial Assistant: Kristy Alaura Acquisitions Editor, Global Editions: Aditee Agarwal Vice President of Marketing: Christy Lesko Director of Field Marketing: Tim Galligan Product Marketing Manager: Bram Van Kempen Field Marketing Manager: Demetrius Hall Marketing Assistant: Jon Bryant Director of Product Management: Erin Gregg Team Lead, Program and Project Management: Scott Disanno Program Manager: Carole Snyder Project Editor, Global Editions: K.K. Neelakantan Project Manager: RPK Editorial Services, Inc.

Senior Specialist, Program Planning and Support: Maura Zaldivar-Garcia Senior Manufacturing Controller, Global Editions: Jerry Kataria Cover Designer: Lumina Datamatics Cover: Shutterstock Manager, Rights and Permissions: Rachel Youdelman Project Manager, Rights and Permissions: William Opaluch Inventory Manager: Meredith Maresca Media Project Manager: Renata Butera Media Production Manager, Global Editions: Vikram Kumar Full-Service Project Management: Deepthi Mohan, iEnergizer Aptara®, Ltd. Composition: Aptara® Corporation

Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published 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 suppliers hereby disclaim all 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 liable 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 other 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 typographical errors. Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time. Partial 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 the Microsoft corporation. The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications. Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsonglobaleditions.com © Pearson Education Limited 2016 The rights of Tony Gaddis, Judy Walters, and Godfrey Muganda to be identified as the authors of this work have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988. Authorized adaptation from the United States edition, entitled Starting Out with C++: Early Objects, 9th Edition, ISBN 9780134400242, by Tony Gaddis, Judy Walters, and Godfrey Muganda published by Pearson Education © 2017. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS. All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners. British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library 10 9 8 7 6 5 4 3 2 1 ISBN 10: 1292157275 ISBN 13: 9781292157276 Typeset in 10/12.5 Sabon LT Pro by iEnergizer Aptara®, Ltd. Printed and bound in Malaysia



Last A-Head

5

Contents at a Glance Preface   15 Chapter 1 Introduction to Computers and Programming   35 Chapter 2 Introduction to C++   61 Chapter 3 Expressions and Interactivity   111 Chapter 4 Making Decisions   189 Chapter 5 Looping   277 Chapter 6 Functions   357 Chapter 7 Introduction to Classes and Objects   441 Chapter 8 Arrays   541 Chapter 9 Searching, Sorting, and Algorithm Analysis   637 Chapter 10 Pointers   679 Chapter 11 More about Classes and Object-Oriented Programming   737 Chapter 12 More on C-Strings and the string Class   849 Chapter 13 Advanced File and I/O Operations   887 Chapter 14 Recursion   949 Chapter 15 Polymorphism and Virtual Functions   983 Chapter 16 Exceptions, Templates, and the Standard Template Library (STL)   1021 Chapter 17 Linked Lists   1071 Chapter 18 Stacks and Queues   1119 Chapter 19 Binary Trees   1159 Appendix A: The ASCII Character Set   1189 Appendix B: Operator Precedence and Associativity   1193 Appendix C: Answers to Checkpoints   1195 Appendix D: Answers to Odd-Numbered Review Questions   1235 Index   1255 5

This page intentionally left blank

Contents

Preface   15

CHAPTER 1 Introduction to Computers and Programming   35

1.1 1.2 1.3 1.4 1.5 1.6 1.7

Why Program?   35 Computer Systems: Hardware and Software   37 Programs and Programming Languages   42 What Is a Program Made of?   47 Input, Processing, and Output   51 The Programming Process   52 Tying It All Together: Hi! It’s Me   57

CHAPTER 2 Introduction to C++   61

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

The Parts of a C++ Program   61 The cout Object   65 The #include Directive   70 Variables and the Assignment Statement   71 Literals   73 Identifiers   75 Integer Data Types   77 Floating-Point Data Types   82 The char Data Type   86 The C++ string Class   90 The bool Data Type   91 Determining the Size of a Data Type   92 More on Variable Assignments and Initialization   93 Scope   95 Arithmetic Operators   96 Comments   100 Programming Style   101 Tying It All Together: Smile!   103 7

8 Contents

CHAPTER 3 Expressions and Interactivity   111

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

The cin Object   111 Mathematical Expressions   118 Data Type Conversion and Type Casting   126 Overflow and Underflow   132 Named Constants   133 Multiple and Combined Assignment   136 Formatting Output   140 Working with Characters and Strings   150 More Mathematical Library Functions   164 Random Numbers   166 Focus on Debugging: Hand Tracing a Program   170 Green Fields Landscaping Case Study—Part 1   172 Tying It All Together: Word Game   175

CHAPTER 4 Making Decisions   189

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

Relational Operators   189 The if Statement   195 The if/else Statement   204 The if/else  if Statement   209 Menu-Driven Programs   217 Nested if Statements   219 Logical Operators   223 Validating User Input   232 More about Blocks and Scope   234 More about Characters and Strings   237 The Conditional Operator   243 The switch Statement   247 Enumerated Data Types   256 Focus on Testing and Debugging: Validating Output Results   259 Green Fields Landscaping Case Study—Part 2   261 Tying It All Together: Fortune Teller   266

CHAPTER 5 Looping   277

5.1 5.2 5.3 5.4 5.5 5.6 5.7

Introduction to Loops: The while Loop   277 Using the while Loop for Input Validation   284 The Increment and Decrement Operators   287 Counters   292 Keeping a Running Total   294 Sentinels   297 The do-while Loop   299

Contents 9



5.8 5.9 5.10 5.11 5.12 5.13 5.14 5.15

The for Loop   305 Focus on Software Engineering: Deciding Which Loop to Use   311 Nested Loops   313 Breaking Out of a Loop   315 Using Files for Data Storage   319 Focus on Testing and Debugging: Creating Good Test Data   335 Central Mountain Credit Union Case Study   338 Tying It All Together: What a Colorful World   342

CHAPTER 6 Functions   357

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

Modular Programming   357 Defining and Calling Functions   358 Function Prototypes   366 Sending Data into a Function   367 Passing Data by Value   372 The return Statement   376 Returning a Value from a Function   377 Returning a Boolean Value   383 Using Functions in a Menu-Driven Program   385 Local and Global Variables   389 Static Local Variables   396 Default Arguments   398 Using Reference Variables as Parameters   402 Overloading Functions   412 The exit() Function   416 Stubs and Drivers   419 Little Lotto Case Study   421 Tying It All Together: Glowing Jack-o-lantern   426

CHAPTER 7 Introduction to Classes and Objects   441

7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 7.11

Abstract Data Types   441 Object-Oriented Programming   443 Introduction to Classes   445 Creating and Using Objects   448 Defining Member Functions   450 Constructors   457 Destructors   463 Private Member Functions   466 Passing Objects to Functions   469 Object Composition   476 Focus on Software Engineering: Separating Class Specification, Implementation,   and Client Code   480

10 Contents



7.12 7.13 7.14 7.15

Structures   487 More about Enumerated Data Types   499 Home Software Company OOP Case Study   503 Introduction to Object-Oriented Analysis and  Design  510 7.16 Screen Control   520 7.17 Tying It All Together: Yoyo Animation   525

CHAPTER 8 Arrays   541

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

Arrays Hold Multiple Values   541 Accessing Array Elements   543 Inputting and Displaying Array Data   545 Array Initialization   552 The Range-Based for loop   559 Processing Array Contents   562 Using Parallel Arrays   573 The typedef Statement   577 Arrays as Function Arguments   577 Two-Dimensional Arrays   587 Arrays with Three or More Dimensions   594 Vectors   597 Arrays of Objects   609 National Commerce Bank Case Study   619 Tying It All Together: Rock, Paper, Scissors   621

CHAPTER 9 Searching, Sorting, and Algorithm Analysis   637

9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8

Introduction to Search Algorithms   637 Searching an Array of Objects   644 Introduction to Sorting Algorithms   647 Sorting an Array of Objects   655 Sorting and Searching Vectors   658 Introduction to Analysis of Algorithms   661 Case Studies   669 Tying It All Together: Secret Messages   669

CHAPTER 10 Pointers   679

10.1 Pointers and the Address Operator   679 10.2 Pointer Variables   681 10.3 The Relationship Between Arrays and  Pointers  685

Contents 11



10.4 10.5 10.6 10.7 10.8 10.9

Pointer Arithmetic   689 Initializing Pointers   690 Comparing Pointers   693 Pointers as Function Parameters   695 Pointers to Constants and Constant Pointers   699 Focus on Software Engineering: Dynamic Memory  Allocation   704 10.10 Focus on Software Engineering: Returning Pointers from  Functions   708 10.11 Pointers to Class Objects and Structures   714 10.12 Focus on Software Engineering: Selecting Members   of Objects   718 10.13 Smart Pointers   720 10.14 Tying It All Together: Pardon Me, Do You Have the Time?   728

CHAPTER 11 More about Classes and Object-Oriented Programming   737

11.1 The this Pointer and Constant Member Functions   737 11.2 Static Members   742 11.3 Friends of Classes   749 11.4 Memberwise Assignment   754 11.5 Copy Constructors   755 11.6 Operator Overloading   764 11.7 Rvalue References and Move Operations   785 11.8 Function Objects and Lambda Expressions   795 11.9 Type Conversion Operators   804 11.10 Convert Constructors   807 11.11 Aggregation and Composition   810 11.12 Inheritance   816 11.13 Protected Members and Class Access   821 11.14 Constructors, Destructors, and Inheritance   826 11.15 Overriding Base Class Functions   831 11.16 Tying It All Together: Putting Data on the World Wide Web   834

CHAPTER 12 More on C-Strings and the string Class   849

12.1 12.2 12.3 12.4 12.5 12.6 12.7

C-Strings   849 Library Functions for Working with C-Strings   854 Conversions Between Numbers and Strings   863 Writing Your Own C-String Handling Functions   867 More about the C++ string Class   873 Advanced Software Enterprises Case Study   876 Tying It All Together: Program Execution Environments   878

12 Contents

CHAPTER 13 Advanced File and I/O Operations   887

13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9

Input and Output Streams   887 More Detailed Error Testing   895 Member Functions for Reading and Writing Files   899 Binary Files   911 Creating Records with Structures   915 Random-Access Files   920 Opening a File for Both Input and Output   927 Online Friendship Connections Case Study: Object Serialization   932 Tying It All Together: File Merging and Color-Coded HTML   937

CHAPTER 14 Recursion   949

14.1 Introduction to Recursion   949 14.2 The Recursive Factorial Function   956 14.3 The Recursive gcd Function   958 14.4 Solving Recursively Defined Problems   959 14.5 A Recursive Binary Search Function   961 14.6 Focus on Problem Solving and Program Design: The QuickSort Algorithm   963 14.7 The Towers of Hanoi   967 14.8 Focus on Problem Solving: Exhaustive and Enumeration Algorithms   970 14.9 Focus on Software Engineering: Recursion versus Iteration   974 14.10 Tying It All Together: Infix and Prefix Expressions   975

CHAPTER 15 Polymorphism and Virtual Functions   983

15.1 15.2 15.3 15.4 15.5 15.6

Type Compatibility in Inheritance Hierarchies   983 Polymorphism and Virtual Member Functions   989 Abstract Base Classes and Pure Virtual Functions   997 Focus on Object-Oriented Programming: Composition versus Inheritance   1003 Secure Encryption Systems, Inc., Case Study   1007 Tying It All Together: Let’s Move It   1010

CHAPTER 16 Exceptions, Templates, and the Standard Template Library (STL)   1021

16.1 16.2 16.3 16.4 16.5 16.6

Exceptions   1021 Function Templates   1033 Class Templates   1041 Class Templates and Inheritance   1046 Introduction to the Standard Template Library   1050 Tying It All Together: Word Transformers Game   1063

Contents 13

CHAPTER 17 Linked Lists   1071

17.1 17.2 17.3 17.4 17.5 17.6 17.7 17.8

Introduction to the Linked List ADT   1071 Linked List Operations   1077 A Linked List Template   1089 Recursive Linked List Operations   1093 Variations of the Linked List   1101 The STL list Container   1102 Reliable Software Systems, Inc., Case Study   1105 Tying It All Together: More on Graphics and Animation   1108

CHAPTER 18 Stacks and Queues   1119

18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8

Introduction to the Stack ADT   1119 Dynamic Stacks   1127 The STL stack Container   1131 Introduction to the Queue ADT   1133 Dynamic Queues   1140 The STL deque and queue Containers   1143 Focus on Problem Solving and Program Design: Eliminating Recursion   1146 Tying It All Together: Converting Postfix Expressions to Infix   1151

CHAPTER 19 Binary Trees   1159

19.1 19.2 19.3 19.4

Definition and Applications of Binary Trees   1159 Binary Search Tree Operations   1163 Template Considerations for Binary Search Trees   1179 Tying It All Together: Genealogy Trees   1179 Appendix A: Appendix B: Appendix C: Appendix D: Index   1255

The ASCII Character Set   1189 Operator Precedence and Associativity   1193 Answers to Checkpoints   1195 Answers to Odd-Numbered Review Questions   1235

14 Contents

Additional Appendices The following appendices are located on the book’s companion web site. Appendix E: A Brief Introduction to Object-Oriented Programming Appendix F: Using UML in 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

Preface 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 experienced student. The book is written with clear, easy-to-understand language and it covers all the necessary ­topics for an introductory programming course. This text is rich in example programs that are concise, practical, 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++0x. In August 2011, it was approved by the International Standards Organization (ISO), and the name of the standard was officially changed to C++11. Most of the popular C++ compilers now support this standard. The new C++11 standard was the primary motivation behind this edition, which introduces many of the new language features. However, a C++11 compiler is not strictly required to use the book. As you progress through the book, you will see C++11 icons in the margins, next to the new features that are introduced. Programs appearing in sections that are not marked with this icon will still compile using an older compiler. The C++11 Topics Introduced in This Edition • The auto key word is introduced in Chapter 2 as a way to simplify complex variable definitions. This key word causes the compiler to infer a variable’s data type from its initialization value.

15

16 Preface

• Chapter 2 also introduces the new long long int and unsigned long long int data types and the LL literal suffix. • Chapter 5 shows how to pass a string object directly to a file stream object’s open member function, without the need to call the c_str() member function. A discussion of the c_str() function still exists for anyone using a legacy compiler. • The range-based for loop is introduced in Chapter 7. This new looping mechanism automatically iterates over each element of an array, vector, or other collection, without the need for a counter variable or a subscript. • Chapter 7 also introduces strongly typed enums. • Chapter 8 introduces new ways to initialize variables and shows how a vector can now be initialized with an initialization list. • Chapter 10 introduces smart pointers and provides examples of how and why to use the new unique_ptr and shared_ptr pointers for safely allocating and working with dynamic memory. • Chapter 10 also introduces the move assignment operator, and the nullptr 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_string functions for converting numeric values to string objects. • Chapter 15 introduces and demonstrates the use of the new override key word that helps prevent subtle overriding errors and the new final key word that prevents a virtual member function from being overridden. • Chapter 16 introduces the new C++11 functions begin(c) and end(c) to specify positions within a collection c where an operation should 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 updating the book to introduce the new C++11 standard, many improvements have been made to make it even more student-friendly. • Updated Material Material has been updated 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 result, new graphics and new or redesigned figures have been added throughout the book where appropriate and new or improved sample programs have been included in a number of chapters. • New Material New material has been added on a number of topics. In addition 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 material on designing classes.

Preface 17

• 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 students more practice using the while loop before introducing do-while and for loops. The Chapter 6 (Functions) material on defining and calling functions has been reorganized to introduce function prototypes earlier and allow main to always be the first function in a client program.

Organization of the Text This text teaches C++ in a step-by-step fashion. Each chapter 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 (Figure P-1) suggests possible sequences of instruction. Chapter 1 covers fundamental hardware, software, and programming 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 structures, repetition structures, 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, should 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 OOP features, can cover Chapter 17 (Linked Lists), followed by Chapters 18 and 19 (Stacks & Queues and Binary Trees), 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.

18 Preface

Figure P-1  Chapter 1 Introduction

Chapters 2–6 Basic Language Elements

Chapter 7 OOP Introduction

Chapter 8 Arrays

Chapter 9 Searching, Sorting, and Algorithm Analysis

Chapter 11 More OOP

Chapter 15 Adv. OOP

Chapter 16 Exceptions, Templates, and STL

Chapter 12 Advanced Strings

Chapter 10 Pointers

Chapter 13 Advanced Files and I/O

Chapter 14 Recursion

Chapter 17 Linked Lists

Chapter 18 Stacks and Queues

Chapter 19 Binary Trees

Preface 19

Brief Overview of Each Chapter Chapter 1: Introduction to Computers and Programming This chapter provides an introduction to the field of computer science and covers the fundamentals of hardware, software, operating systems, programming, problem solving, 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. The Tying It All Together section shows students how to use the cout statement to create a personalized output message. Programming 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. The C++ string class is presented and string objects are used from this point on in the book as the primary method of handling strings. Programming style conventions are introduced, and good programming style is modeled here, as it is throughout the text. The Tying It All Together section lets the student play with simple textbased graphics. Chapter 3: Expressions and Interactivity In this chapter the student learns to write programs that input and handle numeric, character, and string data. The use of arithmetic operators and the creation of mathematical 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 simple output formatting, on data type conversion and type casting, and on using library functions that work with numbers. The Tying It All Together section shows students how to create a simple interactive word game. Chapter 4: Making Decisions Here the student learns about relational expressions and how to control the flow of a program with if , if/else , and if/else  if statements. Logical operators, the conditional operator, and the switch 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 Together section uses random numbers and branching statements to create a fortune telling game.

20 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 chapter 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 should 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 global 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 demonstrated, 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 21

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 algorithms and has an optional section on sorting and searching STL vectors. A brief introduction to algorithm analysis is included, and students are shown how to determine which of two algorithms is more efficient. This chapter’s Tying It All Together section uses both a table lookup and a searching algorithm to encode and decode secret messages. Chapter 10: Pointers This chapter explains how to use pointers. Topics include pointer arithmetic, initialization of pointers, comparison of pointers, pointers and arrays, pointers and functions, dynamic memory allocation, the new nullptr key word, and more. A new section introduces smart pointers and shows how they can be used to avoid memory leaks. The Tying It All Together section demonstrates the use of pointers to access library data structures and functions that return calendar and wall clock time. Chapter 11: More About Classes and Object-Oriented Programming This chapter continues the study of classes and object-oriented programming, covering more advanced topics such as inheritance and object aggregation and composition. Other topics include constant member functions, static members, friends, memberwise assignment, copy constructors, object type conversion operators, convert constructors, operator overloading, move constructors, and move assignment operators. A new section introduces function objects and the C++11 lambda expressions. The Tying It All Together section brings together the concepts of inheritance and convert constructors to build a program that formats the contents of an array to form an HTML table for display on a Web site. Chapter 12: More on C-Strings and the string Class This chapter covers standard library functions for working with characters and C-strings, as well as material on string class functions, functions in the new C++11 string library, and new overloaded to_string functions for converting numeric values to string objects. The Tying It All Together section shows students how to access string-based program environments to obtain information about the computer and the network on which the program is running. Chapter 13: Advanced File and I/O Operations This chapter introduces more advanced topics for working with sequential access text files and introduces random access and binary files. Various modes for opening files are discussed, as well as the many methods for reading and writing their contents. The Tying It All Together program applies many of the techniques c­overed in the chapter to merge two text files into an HTML document for display on the Web, with different colors used to illustrate which file each piece of data came from.

22 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, including recursive functions for computing factorials, finding a greatest common denominator (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 algorithms. 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 compatibility within an inheritance hierarchy, and virtual inheritance. The Tying It All Together section illustrates the use of inheritance and polymorphism to display and animate graphical 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 function and class templates to create generic 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 containers in the Standard Template Library 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 objects, 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 static and dynamic stacks and queues. The operations of stacks and queues are defined, and templates for each ADT are demonstrated. The static array-based stack uses exception-handling to handle stack overflow and underflow, providing a realistic and natural example of defining, throwing, and catching exceptions. The Tying It All Together section discusses strategies 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 operations. 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 23

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 associativity. Appendix C: Answers to Checkpoints  A tool students can use to assess their understanding by comparing their answers to the Checkpoint exercises found throughout the book. The answers to all Checkpoint exercises are included. Appendix D: Answers to Odd-Numbered Review Questions  Another tool 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 Class Design  A brief introduction to the Unified Modeling Language (UML) class diagrams with examples of their use. Appendix G: Multi-Source File Programs  A tutorial on how to create, compile, and link programs with multiple source files. Includes the use of function header files, class specification files, and class implementation files. Appendix H: Multiple and Virtual Inheritance  A self-contained discussion of the C++ concepts of multiple and virtual inheritance for anyone already familiar with single inheritance. Appendix I: Header File and Library Function Reference  A reference for the C++ library functions and header files used in the book. Appendix J: Namespaces  An explanation of namespaces and their purpose, with examples provided on how to define a namespace and access its members. Appendix K: C++ Casts and Run-Time Type Identification  An introduction to different ways of doing type casting in C++ and to run-time type identification. Appendix L: Passing Command Line Arguments  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 M: Binary Numbers and Bitwise Operations  A guide to the binary number system and the C++ bitwise operators, as well as a tutorial on the internal storage of integers. Appendix N: Introduction to Flowcharting  A tutorial that introduces flowcharting and its symbols. It includes handling sequence, selection, case, repetition, and calls to other modules. Sample flowcharts for several of the book’s example programs are presented.

24 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 currently 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 sample 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 material covered in that chapter. VideoNote

VideoNotes A series of online videos, developed specifically for this book, are available for viewing at www.pearsonglobaleditions. com/gaddis. VideoNote icons appear throughout the text, alerting the student to videos about specific topics. Checkpoints 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 appropriate places throughout the text. They are short explanations of interesting or often misunderstood points relevant to the topic at hand. Warnings Warnings caution the student about certain 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 Each chapter presents a thorough and diverse set of review questions, such as fill-in-the-blank and short answer, that and Exercises check the student’s mastery of the basic material 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.

Preface 25

Programming Each chapter offers a pool of programming exercises designed to solidify the student’s knowledge of the topics currently Challenges being studied. In most cases the assignments present real-world problems to be solved. Group Projects There are several group programming projects throughout the text, intended to be constructed by a team of students. One student might build the program’s user interface, while another student writes the mathematical code, and another designs and implements a class the program uses. This process is similar to the way many professional programs are written and encourages teamwork within the classroom. C++ Quick For easy access, a quick reference guide to the C++ language Reference Guide is printed on the inside back cover.

Supplements Student Resources The following items are available on the Gaddis Series resource page at www.pearsonglobaleditions.com/gaddis: • • • • •

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

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

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

Visit the Pearson Education Instructor Resource Center (http://www.pearsonglobaleditions. com/gaddis) for information on how to access them. Practice and Assessment with MyProgrammingLab MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students 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 around the structure of this

26 Preface

textbook. For students, the system automatically 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 comprehensive gradebook 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 interactive 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? The 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 27

Acknowledgments There have been many helping hands 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 University of Wisconsin, River Falls

Fred M. D’Angelo Pima Community College

David Akins El Camino College

Joseph DeLibero Arizona State University

Steve Allan Utah State University

Dennis Fairclough Utah Valley State College

Ijaz A. Awan Savannah State University

Larry Farrer Guilford Technical Community College

John Bierbauer North Central College

James D. Fitzgerald Golden West College

Don Biggerstaff Fayetteville Technical Community ­College

Richard Flint North Central College

Paul Bladek Spokane Falls Community College Chuck Boehm Dean Foods, Inc. Bill Brown Pikes Peak Community College Richard Cacace Pensacola Junior College Randy Campbell Morningside College Stephen P. Carl Wright State University Wayne Caruolo Red Rocks Community College Thomas Cheatham Middle Tennessee State University James Chegwidden Tarrant County College John Cigas Rockhurst University John Cross Indiana University of Pennsylvania

Sheila Foster California State University Long Beach David E. Fox American River College Cindy Fry Baylor University Peter Gacs Boston University Cristi Gale Sterling College James Gifford University of Wisconsin, Stevens Point Leon Gleiberman Touro College Simon Gray Ashland University—Ohio Margaret E. Guertin Tufts University Jamshid Haghighi Guilford Technical Community College Ranette H. Halverson Midwestern State University, Wichita Falls, TX

28 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 J. Sargeant Reynolds

Mike Holland Northern Virginia Community College

Ron McCarty Penn State Erie, The Behrend College

Lister Wayne Horn Pensacola Junior College

Robert McDonald East Stroudsburg University

Richard Hull Lenoir-Rhyne College

James McGuffee Austin Community College

Norman Jacobson University of California, Irvine

M. Dee Medley Augusta State University

Eric Jiang San Diego State University

Barbara Meguro University of Hawaii—Hilo

Yinping Jiao South Texas College

Cathi Chambley-Miller Aiken Technical College

Neven Jurkovic Palo Alto College

Sandeep Mitra SUNY Brockport

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—Rockville

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 Inver Hills Community College

Tino Posillico SUNY Farmingdale

Stephen Leach Florida State University

Mahmoud K. Quweider University of Texas at Brownsville

Parkay Louie Houston Community College

M. Padmaja Rao Francis Marion University

Zhu-qu Lu University of Maine, Presque Isle

Timothy Reeves San Juan College

Tucjer Maney George Mason University

Nancy Ripplinger North Idaho College

Preface 29

Ronald Robison Arkansas Tech University

Sam Y. Sung South Texas College

Caroline St. Clair North Central College

Mark Swanson Red Wing Technical College

Dolly Samson Weber State University

Martha Tillman College of San Mateo

Kate Sanders Rhode Island College

Maya Tolappa Waubonsee Community College

Tim Scheemaker Onondaga Community College

Delores Tull Itawamba Community College

Lalchand Shimpi Saint Augustine’s College

Rober Tureman Paul D. Camp Community College

Sung Shin South Dakota State University

Jane Turk LaSalle University

Barbara A. Smith University of Dayton

Sylvia Unwin Bellevue Community College

Garth Sorenson Snow College

Stewart Venit California State University, Los Angeles

Donald Southwell Delta College

David Walter Virginia State University

Daniel Spiegel Kutztown University

Ju Wang Virginia State University

Ray Springston University of Texas at Arlington

Doug White University of Northern Colorado

Kirk Stephens Southwestern Community College

Chris Wild Old Dominion University

Cherie Stevens South Florida Community College

Catherine Wyman DeVry Institute of Technology, Phoenix

Joe Struss Des Moines Area Community College

Sherali Zeadally University of the District of Columbia

Hong Sung University of Central Oklahoma

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 production of this book. We also want to thank our project manager, Rose Kernan, who helped everything run smoothly, 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!

30 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 Haywood Community 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 Institute 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 International 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. He 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: Tkemot/Shutterstock Figure 1-2g: Illustration of Hard disk drive HDD isolated on white background with soft shadow: Vitaly Korovin/Shutterstock Figure 1-2h: Small computer speakers isolated on a white background: StockPhotosArt/Shutterstock Figure 1-2i: Color Printer: Jocic/Shutterstock Figure 1-2j: Four monitors. Vector: Art gallery/Shutterstock Figure 1-2k: Stick of computer random access memory (RAM): Peter Guess/Shutterstock Figure 1-2l: 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

Preface 31

Acknowledgments for the Global Edition Pearson would like to thank and acknowledge the following people for their contributions to the Global Edition. Contributors Moumita Mitra Manna Bangabasi College Reviewers Chitra Dhawale P.R. Pote College of Engineering and Management Ela Kashyap Amity University

Muthuraj M. Timothy Yap Multimedia University

This page intentionally left blank

To improving results

Through the power of practice and immediate personalized feedback, MyProgrammingLab helps improve your students’ performance.

PROGRAMMING PRACTICE With MyProgrammingLab, your students will gain first-hand programming experience in an interactive online environment.

IMMEDIATE, PERSONALIZED FEEDBACK MyProgrammingLab automatically detects errors in the logic and syntax of their code submission and offers targeted hints that enables students to figure out what went wrong and why.

GRADUATED COMPLEXITY MyProgrammingLab breaks down programming concepts into short, understandable sequences of exercises. Within each sequence the level and sophistication of the exercises increase gradually but steadily.

DYNAMIC ROSTER Students’ submissions are stored in a roster that indicates whether the submission is correct, how many attempts were made, and the actual code submissions from each attempt.

PEARSON eTEXT The Pearson eText gives students access to their textbook anytime, anywhere

STEP-BY-STEP VIDEONOTE TUTORIALS These step-by-step video tutorials enhance the programming concepts presented in select Pearson textbooks. For more information and titles available with MyProgrammingLab, please visit www.myprogramminglab.com. Copyright © 2017 Pearson Education, Inc. or its affiliate(s). All rights reserved. HELO88173 • 11/15

This page intentionally left blank

CHAPTER

1

Introduction to Computers and Programming

T OPICS 1.1 Why Program?

1.4 What Is a Program Made of?

1.2 Computer Systems: Hardware and Software

1.5 Input, Processing, and Output

1.3 Programs and Programming Languages

1.7 Tying It All Together: Hi! It’s Me

1.1

1.6 The Programming Process

Why Program? CONCEPT: Computers can do many different jobs because they are programmable. Think about some of the different ways that people use computers. In school, students use computers for tasks such as writing papers, searching for articles, sending e-mail, and participating in online classes. At work, people use computers to analyze data, make presentations, conduct business transactions, communicate with customers and coworkers, control machines in manufacturing facilities, and do many other things. At home, people use computers for tasks such as paying bills, shopping online, social ­networking, and playing games. And don’t forget that smart phones, iPods®, car navigation systems, and many other devices are computers as well. The uses of computers are almost limitless in our everyday lives. Computers can do such a wide variety of things because they can be programmed. This means that computers are not designed to do just one job, but to do any job that their programs tell them to do. A program is a set of instructions that a computer follows to perform a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two commonly used programs.

35

36

Chapter 1

Introduction to Computers and Programming

Figure 1-1  A Word Processing Program and a Presentation Program

Programs are commonly referred to as software. Software is essential to a computer because without software, a computer can do nothing. All of the software that we use to make our computers useful is created by individuals known as programmers or software developers. A programmer, or software developer, is a person with the training and skills necessary to design, create, and test computer programs. Computer programming is an exciting and rewarding career. Today you will find programmers working in business, medicine, government, law enforcement, agriculture, academics, entertainment, and almost every other field. Computer programming is both an art and a science. It is an art because every aspect of a program should be designed with care and judgment. Listed below are a few of the things that must be designed for any real-world computer program: • • • • • •

The logical flow of the instructions The mathematical procedures The appearance of the screens The way information is presented to the user The program’s “user-friendliness” Manuals and other forms of written documentation

There is also a scientific, or engineering side to programming. Because programs rarely work right the first time they are written, a lot of experimentation, correction, and redesigning is required. This demands patience and persistence of the programmer. Writing software demands discipline as well. Programmers must learn special ­languages like C++ because computers do not understand English or other human languages. Languages such as C++ have strict rules that must be carefully followed. Both the artistic and scientific nature of programming makes writing computer ­software like designing a car. Both cars and programs should be functional, efficient, powerful, easy to use, and pleasing to look at.



1.2  Computer Systems: Hardware and Software

1.2

Computer Systems: Hardware and Software CONCEPT: All computer systems consist of similar hardware devices and software components. This section provides an overview of standard computer hardware and software organization.

Hardware Hardware refers to the physical components of a computer. A computer, as we generally think of it, is not an individual device but a system of devices. Like the instruments in a symphony orchestra, each device plays its own part. A typical computer system consists of the following major components: • • • • •

The central processing unit (CPU) Main memory (random-access memory, or RAM) Secondary storage devices Input devices Output devices

The organization of a computer system is depicted in Figure 1-2. Figure 1-2 

Central Processing Unit Output Devices

Input Devices

Main Memory (RAM) Secondary Storage Devices

37

38

Chapter 1

Introduction to Computers and Programming

The CPU When a computer is performing the tasks that a program tells it to do, we say that the computer is running or executing the program. The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU is the most important component in a computer because without it the computer could not run software. In the earliest computers, CPUs were huge devices made of electrical and mechanical components such as vacuum tubes and switches. Today’s CPUs, known as microprocessors, are tiny chips small enough to be held in the palm of your hand. In addition to being much smaller than the old electromechanical CPUs in early computers, today’s microprocessors are also much more powerful. The CPU’s job is to fetch instructions, follow the instructions, and produce some result. Internally, the central processing unit consists of two parts: the control unit and the arithmetic and logic unit (ALU). The control unit coordinates all of the computer’s operations. It is responsible for determining where to get the next instruction and for regulating the other major components of the computer with control signals. The ­arithmetic and logic unit, as its name suggests, is designed to perform mathematical operations. The organization of the CPU is shown in ­Figure 1-3. Figure 1-3  Central processing unit (CPU)

Instruction input

Arithmetic and logic unit (ALU)

Result output

Control unit

A program is a sequence of instructions stored in the computer’s memory. When a computer is running a program, the CPU is engaged in a process known formally as the fetch/decode/execute cycle. The steps in the fetch/decode/execute cycle are as follows: Fetch The CPU’s control unit fetches, from main memory, the next instruction in the sequence of program instructions. Decode The instruction is encoded in the form of a number. The control unit decodes the instruction and generates an electronic signal. Execute The signal is routed to the appropriate component of the computer (such as the ALU, a disk drive, or some other device). The signal causes the c­ omponent to perform an operation. These steps are repeated as long as there are instructions to perform.



1.2  Computer Systems: Hardware and Software

Main Memory You can think of main memory as the computer’s work area. This is where the ­computer stores a program while the program is running, as well as the data that the program is working with. For example, suppose you are using a word processing ­program to write an essay for one of your classes. While you do this, both the word processing program and the essay are stored in main memory. Main memory is commonly known as random-access memory or RAM. It is called this because the CPU is able to quickly access data stored at any random location in this memory. RAM is usually a volatile type of memory that is used only for temporary storage while a program is running. When the computer is turned off, the contents of RAM are erased. Inside your computer, RAM is stored in small chips. A computer’s memory is divided into tiny storage cells known as bytes. One byte is enough memory to store just a single letter of the alphabet or a small number. In order to do anything meaningful, a computer has to have lots of bytes. Most computers today have millions, or even billions, of bytes of memory. Each byte is divided into eight smaller storage locations known as bits. The term bit stands for binary digit. Computer scientists usually think of bits as tiny switches that can be either on or off. Bits aren’t actual “switches,” however, at least not in the conventional sense. In most computer systems, bits are tiny electrical components that can hold either a positive or a negative charge. Computer scientists think of a positive charge as a switch in the on position and a negative charge as a switch in the off position. Each byte is assigned a unique number known as an address. The addresses are ordered from lowest to highest. A byte is identified by its address, in much the same way a post office box is identified by an address, so that the data stored there can be located. ­Figure 1-4 shows a group of memory cells with their addresses. The number 149 is stored in the cell at address 16, and the number 72 is stored at address 23. Figure 1-4  0

1

2

3

4

5

6

10

11

12

13

14

15

16

20

21

22

23

24

25

26

72

149

7

8

9

17

18

19

27

28

29

Secondary Storage Secondary storage is a type of memory that can hold data for long periods of time— even when there is no power to the computer. Frequently used programs are stored in secondary memory and loaded into main memory as needed. Important information, such as word processing documents, payroll data, and inventory figures, is saved to secondary storage as well. The most common type of secondary storage device is the disk drive. A disk drive stores data by magnetically encoding it onto a circular disk. Most computers have a

39

40

Chapter 1

Introduction to Computers and Programming

disk drive mounted inside their case. External disk drives, which connect to one of the computer’s communication ports, are also available. External disk drives can be used to create backup copies of important data or to move data to another ­computer. In addition to external disk drives, many types of devices have been created for copying data and for moving it to other computers. The most commonly used devices today are USB flash drives. These are small devices that plug into the computer’s USB (universal serial bus) port and appear to the system as a disk drive. These drives, which use flash memory to store data, are inexpensive, reliable, and small enough to be carried in your pocket. Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are also popular for data storage. Data is not recorded magnetically on an optical disc, but rather is encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect the pits and thus read the encoded data. Optical discs hold large amounts of data, and because recordable CD and DVD drives are now commonplace, they are good media for creating backup copies of data. Input Devices Input is any information the computer collects from the outside world. The device that collects the information and sends it to the computer is called an input device. Common input devices are the keyboard, mouse, touch screen, scanner, digital camera, and microphone. Disk drives, CD/DVD drives, and USB flash drives can also be considered input devices because programs and information can be retrieved from them and loaded into the computer’s memory. Output Devices Output is any information the computer sends to the outside world. It might be a sales report, a list of names, or a graphic image. The information is sent to an output device, which formats and presents it. Common output devices are computer screens, printers, and speakers. Disk drives, USB flash drives, and CD/DVD recorders can also be considered output devices because the CPU can send information to them to be saved.

Software If a computer is to function, software is needed. Everything that a computer does, from the time you turn the power switch on until you shut the system down, is under the control of software. There are two general categories of software: system software and application software. Most computer programs clearly fit into one of these two ­categories. Let’s take a closer look at each. System Software The programs that control and manage the basic operations of a computer are generally referred to as system software. System software typically includes the following types of programs:



1.2  Computer Systems: Hardware and Software

• Operating Systems An operating system is the most fundamental set of programs on a computer. The operating system controls the internal operations of the computer’s hardware, manages all the devices connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other programs to run on the computer. • Utility Programs A utility program performs a specialized task that enhances the computer’s ­operation or safeguards data. Examples of utility programs are virus scanners, file-compression programs, and data-backup programs. • Software Development Tools The software tools that programmers use to create, modify, and test software are referred to as software development tools. Compilers and integrated development environments, which we discuss later in this chapter, are examples of programs that fall into this category. Application Software Programs that make a computer useful for everyday tasks are known as application software, or application programs. These are the programs that people normally spend most of their time running on their computers. Figure 1-1, at the beginning of this chapter, shows screens from two commonly used applications Microsoft Word, a word processing program, and Microsoft PowerPoint, a presentation program. Some other examples of application software are spreadsheet programs, e-mail programs, Web browsers, and game programs. Checkpoint 1.1

Why is the computer used by so many different people, in so many different professions?

1.2

List the five major hardware components of a computer system.

1.3

Internally, the CPU consists of what two units?

1.4

Describe the steps in the fetch/decode/execute cycle.

1.5

What is a memory address? What is its purpose?

1.6

Explain why computers have both main memory and secondary storage.

1.7

What are the two general categories of software?

1.8

What fundamental set of programs controls the internal operations of the ­computer’s hardware?

1.9

What do you call a program that performs a specialized task, such as a virus scanner, a file-compression program, or a data-backup program?

1.10 Word processing programs, spreadsheet programs, e-mail programs, Web browsers, and game programs belong to what category of software?

41

42

Chapter 1

1.3

Introduction to Computers and Programming

Programs and Programming Languages CONCEPT: A program is a set of instructions a computer follows in order to perform a task. A programming language is a special language used to write computer programs.

What Is a Program? Computers are designed to follow instructions. A computer program is a set of instructions that tells the computer how to solve a problem or perform a task. For example, suppose we want the computer to calculate someone’s gross pay. Here is a list of things the computer might do: 1. Display a message on the screen asking “How many hours did you work?” 2. Wait for the user to enter the number of hours worked. Once the user enters a number, store it in memory. 3. Display a message on the screen asking “How much do you get paid per hour?” 4. Wait for the user to enter an hourly pay rate. Once the user enters a number, store it in memory. 5. Multiply the number of hours by the amount paid per hour, and store the result in memory. 6. Display a message on the screen that tells the amount of money earned. The ­message must include the result of the calculation performed in step 5. Collectively, these instructions are called an algorithm. An algorithm is a set of welldefined steps for performing a task or solving a problem. Notice these steps are ordered sequentially. Step 1 should be performed before step 2, and so forth. It is important that these instructions be performed in their proper sequence. Although a person might easily understand the instructions in the pay-calculating algorithm, it is not ready to be executed on a computer because a computer’s CPU can only process instructions written in machine language. A machine language program consists of a sequence of binary numbers (numbers consisting of only 1s and 0s), which the CPU interprets as commands. Here is an example of what a machine language instruction might look like: 1011010000000101

As you can imagine, encoding an algorithm in machine language would be tedious and difficult. In addition, each different type of CPU has its own machine language. So if you wrote a machine language program for computer A and then wanted to run it on a computer B that has a different type of CPU, you would have to rewrite the program in computer B’s machine language. Programming languages, which use words instead of numbers, were invented to ease the task of programming. A program can be written in a programming language such as C++, which is much easier to understand and write than machine language. Programmers can then save their programs in text files and use special software to convert them to machine language. Program 1-1 shows how the pay-calculating algorithm might be written in C++.



1.3  Programs and Programming Languages

NOTE:   The line numbers shown in Program 1-1 are not part of the program. This book shows line numbers in all program listings to help point out specific parts of the program.

Program 1-1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

// This program calculates the user's pay. #include using namespace std; int main() { double hours, rate, pay; // Get the number of hours worked. cout > hours; // Get the hourly pay rate. cout > rate; // Calculate the pay. pay = hours * rate; // Display the pay. cout hours; // Determine how many hours to charge for hours = hours < MIN_HOURS ? MIN_HOURS : hours; // Calculate and display the charges charges = PAY_RATE * hours; cout hours[count] ) count++; // Close the file. inputFile.close(); // Display the contents of the array. cout playerChoice; if (computerChoice == playerChoice) { cout amount) largestIndex––; if (amount == 0 || largestIndex == 0) return 1; // Number of ways to make change for amount int nWays = 0; // Number of coins of largest index to use int nCoins = 0 ; while (nCoins left, num); else insert(tree−>right, num); }

Note that the function is passed a reference to a pointer because the pointer passed may need to be modified by the function. This is also the reason the remove and ­makeDeletion functions are passed their parameters by reference. NOTE:   The shape of the tree shown in Figure 19-5 is determined by the order in which the values are inserted. The root node holds the value 5 because that was the first value inserted. By stepping through the function, you can see how the other nodes came to appear in their depicted positions.

Traversing the Tree There are three common methods for traversing a nonempty binary tree and processing the value of each node: inorder, preorder, and postorder. Each of these methods is best implemented as a recursive function. The algorithms are described as follows.

1167

1168

Chapter 19

Binary Trees

• Inorder traversal 1. The node’s left subtree is traversed. 2. The node’s data is processed. 3. The node’s right subtree is traversed. • Preorder traversal 1. The node’s data is processed. 2. The node’s left subtree is traversed. 3. The node’s right subtree is traversed. • Postorder traversal 1. The node’s left subtree is traversed. 2. The node’s right subtree is traversed. 3. The node’s data is processed. The IntBinaryTree class can display all the values in the tree using all three of these algorithms. The algorithms are initiated by the following inline public member functions: void { void { void {

showInOrder(void) displayInOrder(root); } showPreOrder() displayPreOrder(root); } showPostOrder() displayPostOrder(root); }

Each of the public member functions calls a recursive private member function and passes the root pointer as an argument. The recursive functions are very simple and straightforward: void IntBinaryTree::displayInOrder(TreeNode *tree) const { if (tree) { displayInOrder(tree−>left); cout value right); } } void IntBinaryTree::displayPreOrder(TreeNode *tree) const { if (tree) { cout value left); displayPreOrder(tree−>right); } } void IntBinaryTree::displayPostOrder(TreeNode *tree) const { if (tree) { displayPostOrder(tree−>left); displayPostOrder(tree−>right); cout value right; } return false; }

Program 19-3 demonstrates this function. Program 19-3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

// This program builds a binary tree with 5 nodes. // The search function determines if the // value 3 is in the tree. #include #include "IntBinarytree.h" using namespace std; int main() { IntBinaryTree tree; cout tree−>value) remove(tree−>right,num); else // We have found the node to delete. makeDeletion(tree); }

The makeDeletion function is designed to remove the root node of the binary search tree passed to it as an argument, leaving a binary search tree consisting of the ­remaining nodes. Let us take a look at the logic behind makeDeletion. There are a number of cases to consider: 1. The root of the tree passed to makeDeletion has no children. In this case, we delete the root node and replace the tree with nullptr. 2. The root of the tree has only one child. In this case, we delete the root node and replace the tree with the child of the deleted root: TreeNode *nodeToDelete = tree; if (tree−>right == nullptr) tree = tree−>left; else if (tree−>left == nullptr) tree = tree−>right;

Note that this code works for the first case as well. 3. The tree passed to makeDelete has two children. The deletion of the root node would leave two subtrees, and we need to do something with both of them. The strategy we adopt is to combine the two subtrees into one binary search tree and then replace the original tree with the tree built from the combined subtrees. As shown in Figure 19-9, we can do this by attaching the left subtree of the original tree as the left subtree of the least node in the right subtree of the original tree. Here is the code for the entire function.

1173

1174

Chapter 19

Binary Trees void IntBinaryTree::makeDeletion(TreeNode *&tree) { // Used to hold node that will be deleted TreeNode *nodeToDelete = tree; // Used to locate the point where the // left subtree is attached TreeNode *attachPoint; if (tree−>right == nullptr) { // Replace tree with its left subtree tree = tree−>left; } else if (tree−>left == nullptr) { // Replace tree with its right subtree tree = tree−>right; } else //The node has two children { // Move to right subtree attachPoint = tree−>right; // Locate the smallest node in the right subtree // by moving as far to the left as possible while (attachPoint−>left != nullptr) attachPoint = attachPoint−>left; // Attach the left subtree of the original tree // as the left subtree of the smallest node // in the right subtree attachPoint−>left = tree−>left; // Replace the original tree with its right subtree tree = tree−>right; } // Delete root of original tree delete nodeToDelete; }

Program 19-4 demonstrates these functions. Program 19-4 1 2 3 4 5 6 7

// This program builds a binary tree with 5 nodes. // The deleteNode function is used to remove 2 of them. #include #include "IntBinaryTree.h" using namespace std; int main() (program continues)



19.2  Binary Search Tree Operations Program 19-4 8 { 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 }

(continued)

IntBinaryTree tree; cout left); destroySubtree(tree−>right); // Delete the node at the root delete tree; } //*************************************************** // searchNode determines if a value is present in * // the tree. If so, the function returns true. * // Otherwise, it returns false. * //*************************************************** bool IntBinaryTree::search(int num) const { TreeNode *tree = root; while (tree) { if (tree−>value == num) return true; else if (num < tree−>value) tree = tree−>left; else tree = tree−>right; } return false; } //******************************************** // remove deletes the node in the given tree * // that has a value member the same as num. * //********************************************



19.2  Binary Search Tree Operations 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 121

void IntBinaryTree::remove(TreeNode *&tree, int num) { if (tree == nullptr) return; if (num < tree−>value) remove(tree−>left, num); else if (num > tree−>value) remove(tree−>right,num); else // We have found the node to delete makeDeletion(tree); } //*********************************************************** // makeDeletion takes a reference to a tree whose root * // is to be deleted. If the tree has a single child, * // the tree is replaced by the single child after the * // removal of its root node. If the tree has two children * // the left subtree of the deleted node is attached at * // an appropriate point in the right subtree, and then * // the right subtree replaces the original tree. * //*********************************************************** void IntBinaryTree::makeDeletion(TreeNode *&tree) { // Used to hold node that will be deleted TreeNode *nodeToDelete = tree; // Used to locate the point where the // left subtree is attached TreeNode *attachPoint; if (tree−>right == nullptr) { // Replace tree with its left subtree tree = tree−>left; } else if (tree−>left == nullptr) { // Replace tree with its right subtree tree = tree−>right; } else //The node has two children { // Move to right subtree attachPoint = tree−>right; // Locate the smallest node in the right subtree // by moving as far to the left as possible while (attachPoint−>left != nullptr) attachPoint = attachPoint−>left; // Attach the left subtree of the original tree // as the left subtree of the smallest node

1177

1178

Chapter 19

Binary Trees 122 123 124 125 126 127 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 172 173

// in the right subtree attachPoint−>left = tree−>left; // Replace the original tree with its right subtree tree = tree−>right; } // Delete root of original tree delete nodeToDelete; } //********************************************************* // This function displays the values stored in a tree * // in inorder. * //********************************************************* void IntBinaryTree::displayInOrder(TreeNode *tree) const { if (tree) { displayInOrder(tree−>left); cout value right); } } //********************************************************* // This function displays the values stored in a tree * // in inorder. * //********************************************************* void IntBinaryTree::displayPreOrder(TreeNode *tree) const { if (tree) { cout value left); displayPreOrder(tree−>right); } } //********************************************************* // This function displays the values stored in a tree * // in postorder. * //********************************************************* void IntBinaryTree::displayPostOrder(TreeNode *tree) const { if (tree) { displayPostOrder(tree−>left); displayPostOrder(tree−>right); cout value name = name; gender = g; } Person *addChild(string name, Gender g); Person *addChild(Person *p); friend ostream &operator addParent(this); // I am a parent of this child children.push_back(child); // This is one of my children return child; } //************************************************************ // Add a child to the list of children for this person * //************************************************************ Person *Person::addChild(Person* child) { child−>addParent(this); // I am a parent of this child children.push_back(child); // This is one of my children return child; } //********************************************************* // Return a pointer to the specified parent * //********************************************************* Person *Person::getParent(int k) const { if (k < 0 || k >= parents.size()) { cout ? @

1189

1190

Appendix A

The ASCII Character Set

Dec

Printable 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 I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x

Dec

Printable ASCII Characters Hex Oct Character

121 122 123 124 125 126

79 7a 7b 7c 7d 7e

Dec

Extended ASCII Characters Hex Oct Character

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 8a 8b 8c 8d 8e 8f 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab

171 172 173 174 175 176

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

y z { | } ˜

Ç ü é â ä à å ç ê ë è ï î ì Ä Å É æ Æ ô ö ò û ù ÿ Ö Ü ¢ £ ù û

ƒ

á í ó ú ñ Ñ

ª º

¿ © Ñ ´



The ASCII Character Set

Dec

Extended ASCII Characters Hex Oct Character

Dec

Extended ASCII Characters Hex Oct Character

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

ac ad ae af b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf d0 d1 d2 d3 d4 d5

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

d6 d7 d8 d9 da db dc dd de df e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff

254 255 256 257 260 261 262 263 264 265 266 267 270 271 272 273 274 275 276 277 300 301 302 303 304 305 306 307 310 311 312 313 314 315 316 317 320 321 322 323 324 325

¨ ¡ » ∞ ± ≤ ≥ ¥ μ ∂ ∑ Π π ∫

a

o Ω æ ø ¿ ¡ ¬ √ ƒ ≈ Δ » … _ À Ã Õ Œ œ – ——

“ ” ‘ ’

326 327 330 331 332 333 334 335 336 337 340 341 342 343 344 345 346 347 350 351 352 353 354 355 356 357 360 361 362 363 364 365 366 367 370 371 372 373 374 375 376 377

÷ ◊ ÿ Ÿ / ‹ › fi fl ‡ · ‚



‰ Â Ê Á Ë È Í Î Ï Ì Ó Ô Ò Ú Û Ù ı ˆ ˜ ¯ ˘ ˙ · ¸ ˝ ˛

1191

This page intentionally left blank

A pp e n d i x

B

Operator Precedence and Associativity

The operators are shown in order of precedence, from highest to lowest. Operator ::

Associativity unary: left to right binary: right to left

() [] -> .

left to right

++ − + − ! ˜ (type) * & sizeof

right to left

* / %

left to right

+ −

left to right

>

left to right

< >=

left to right

== !=

left to right

&

left to right

ˆ

left to right

|

left to right

&&

left to right

||

left to right

?:

right to left

= += −= *= /= %= &= ˆ= |= =

right to left

,

left to right

1193

This page intentionally left blank

Appendix

C

Answers to Checkpoints

Chapter 1 1.1

Because the computer can be programmed to do so many different tasks

1.2

The central processing unit (CPU), main memory (RAM), secondary storage devices, input devices, and output devices

1.3

Arithmetic and logic unit (ALU) and control unit

1.4

Fetch: The CPU’s control unit fetches the program’s next instruction from main memory.



Decode: The control unit decodes the instruction, which is encoded in the form of a number. An electrical signal is generated.



Execute: The signal is routed to the appropriate component of the computer, which causes a device to perform an operation.

1.5

A memory address is a unique number assigned to each storage location in memory. Its purpose is to allow data stored in RAM to be located.

1.6

Program instructions and data are stored in main memory while the program is running. Main memory is volatile and loses its contents when power is removed from the computer. Secondary storage holds data for long periods of time—even when there is no power to the computer.

1.7

Operating systems and application software

1.8

The operating system

1.9

A utility program

1.10 Application software or application programs 1.11 A set of well-defined steps for performing a task or solving a problem 1.12 To ease the task of programming. Programs may be written in a programming language, then converted to machine language. 1.13 A low-level language is close to the level of the computer and resembles the system’s numeric machine language. A high-level language is closer to the level of human readability and resembles natural languages. 1.14 That a program may be written on one type of computer and run on another type

1195

1196

Appendix C

Answers to Checkpoints

1.15 The preprocessor reads the source file, searching for commands that begin with the # symbol. These are commands that cause the preprocessor to modify the source file in some way. The compiler translates each source code instruction into the appropriate machine language instruction and creates an object file. The linker combines the object file with necessary library routines to create an executable file. 1.16 Source file: Contains program statements written by the programmer.

Object file: Contains machine language instructions generated by the compiler.



Executable file: Contains code ready to run on the computer. Includes the machine language from an object file and the necessary code from library routines.

1.17 A programming environment that includes a text editor, compiler, debugger, and other utilities, integrated into one package 1.18 A key word has a special purpose and is defined as part of a programming language. A programmer-defined symbol is a word or name defined by the programmer. 1.19 Operators perform operations on one or more operands. Punctuation symbols mark the beginning or ending of a statement, or separate items in a list. 1.20 A line is a single line as it appears in the body of a program. A statement is a complete instruction that causes the computer to perform an action. It may be written on 1 or more lines. 1.21 Because their contents may be changed while the program is running. 1.22 It is overwritten by the new value. The old value is “lost”. 1.23 The variable must be defined in a declaration. 1.24 Input, processing, and output 1.25 The program’s purpose, the information to be input, the processing to take place, and the desired output. 1.26 To imagine what the computer screen looks like while the program is running. This helps define input and output. 1.27 A chart that depicts the logical steps of the program in a hierarchical fashion 1.28 A “language” that is a cross between human language and programming languages that is used to express algorithms. 1.29 High-level psuedocode just lists the steps a program must carry out. Detailed psuedocode shows the variables, logic, and computations needed to create the program. 1.30 It translates each source code statement into the appropriate machine language statements. 1.31 A mistake that causes a program to produce erroneous results. A logic error occurs when what the programmer means for the program to do does not match what the code actually instructs the program to do. 1.32 An error that occurs while the program is running when the system is asked to perform an action it cannot carry out. 1.33 The programmer steps through each statement in the program from beginning to end. The contents of variables are recorded, and screen output is sketched.



Answers to Checkpoints

Chapter 2 2.1

// A crazy mixed up program #include using namespace std; int main() { cout