137 111 10MB
English Pages [1397] Year 2021
STARTING OUT WITH
C++
From Control Structures through Objects TENTH EDITION
This page intentionally left blank
STARTING OUT WITH
C++
From Control Structures through Objects TENTH EDITION
Tony Gaddis Haywood Community College
Please contact https://support.pearson.com/getsupport/s/contactsupport with any queries on this content Copyright © 2021, 2013, 2010 by Pearson Education, Inc. or its affiliates, 221 River Street, Hoboken, NJ 07030. All Rights Reserved. Manufactured in the United States of America. This publication is protected by copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise. For information regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights and Permissions department, please visit www.pearsoned.com/permissions/. Acknowledgments of third-party content appear on the appropriate page within the text. PEARSON, ALWAYS LEARNING, and MYLAB are exclusive trademarks owned by Pearson Education, Inc. or its affiliates in the U.S. and/or other countries. Unless otherwise indicated herein, any third-party trademarks, logos, or icons that may appear in this work are the property of their respective owners, and any references to third-party trademarks, logos, icons, or other trade dress are for demonstrative or descriptive purposes only. Such references are not intended to imply any sponsorship, endorsement, authorization, or promotion of Pearson’s products by the owners of such marks, or any relationship between the owner and Pearson Education, Inc., or its affiliates, authors, licensees, or distributors. Library of Congress Cataloging-in-Publication Data Names: Gaddis, Tony, author. Title: Starting out with C++ : from control structures through objects / Tony Gaddis, Haywood Community College. Description: Tenth edition. | Hoboken, NJ : Pearson, [2021] | Includes index. Identifiers: LCCN 2019059946 (print) | LCCN 2019059947 (ebook) | ISBN 9780135921043 (paperback) | ISBN 9780135928349 (epub) Subjects: LCSH: C++ (Computer program language) Classification: LCC QA76.73.C153 G334 2021 (print) | LCC QA76.73.C153 (ebook) | DDC 005.13/3--dc23 LC record available at https://lccn.loc.gov/2019059946 LC ebook record available at https://lccn.loc.gov/2019059947
ScoutAutomatedPrintCode
Print Offer ISBN-13: 978-0-13-592829-5 ISBN-10: 0-13-592829-X
Contents at a Glance Preface
xvii
CHAPTER 1
Introduction to Computers and Programming 1
CHAPTER 2
Introduction to C++ 27
CHAPTER 3
Expressions and Interactivity 87
CHAPTER 4
Making Decisions 153
CHAPTER 5
Loops and Files 237
CHAPTER 6
Functions
CHAPTER 7
Arrays and Vectors 387
CHAPTER 8
Searching and Sorting Arrays 471
CHAPTER 9
Pointers
CHAPTER 10
Characters, C-Strings, and More about the string Class
CHAPTER 11
Structured Data
CHAPTER 12
Advanced File Operations 675
CHAPTER 13
Introduction to Classes 751
CHAPTER 14
More about Classes 849
CHAPTER 15
Inheritance, Polymorphism, and Virtual Functions 941
CHAPTER 16
Exceptions and Templates 1023
CHAPTER 17
The Standard Template Library
CHAPTER 18
Linked Lists 1169
CHAPTER 19
Stacks and Queues 1213
CHAPTER 20
Recursion
CHAPTER 21
Binary Trees 1309
309
511 565
621
1065
1271
Appendix A: The ASCII Character Set 1339 Appendix B: Operator Precedence and Associativity 1341 v
vi
Contents at a Glance
Quick References 1343
Online
Index
1345
Credit
1363
The following appendices are available at www.pearsonhighered.com/ cs-resources. Appendix C: Introduction to Flowcharting Appendix D: Using UML in Class Design Appendix E: Namespaces Appendix F: Passing Command Line Arguments Appendix G: Binary Numbers and Bitwise Operations Appendix H: STL Algorithms Appendix I: Multi-Source File Programs Appendix J: Stream Member Functions for Formatting Appendix K: Unions Appendix L: Answers to Checkpoints Appendix M: Answers to Odd Numbered Review Questions Case Study 1: C-String Manipulation Case Study 2: High Adventure Travel Agency—Part 1 Case Study 3: Loan Amortization Case Study 4: Creating a String Class Case Study 5: High Adventure Travel Agency—Part 2 Case Study 6: High Adventure Travel Agency—Part 3 Case Study 7: Intersection of Sets Case Study 8: Sales Commission
Contents Preface CHAPTER 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7
CHAPTER 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 2.13 2.14 2.15 2.16 2.17
xvii
Introduction to Computers and Programming 1 Why Program? 1 Computer Systems: Hardware and Software 2 Programs and Programming Languages 8 What Is a Program Made of? 14 Input, Processing, and Output 17 The Programming Process 18 Procedural and Object-Oriented Programming 22 Review Questions and Exercises 24 Introduction to C++ 27 The Parts of a C++ Program 27 The cout Object 31 The #include Directive 37 Variables, Literals, and Assignment Statements 39 Identifiers 43 Integer Data Types 44 The char Data Type 50 The C++ string Class 54 Floating-Point Data Types 56 The bool Data Type 59 Determining the Size of a Data Type 60 More about Variable Assignments and Initialization 61 Scope 64 Arithmetic Operators 64 Comments 72 Named Constants 74 Programming Style 76 Review Questions and Exercises 78 Programming Challenges 83
vii
viii
Contents
CHAPTER 3 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11
CHAPTER 4 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15 4.16 4.17
CHAPTER 5 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12
Expressions and Interactivity 87 The cin Object 87 Mathematical Expressions 93 When You Mix Apples and Oranges: Type Conversion 102 Overflow and Underflow 104 Type Casting 105 Multiple Assignment and Combined Assignment 108 Formatting Output 112 Working with Characters and string Objects 122 More Mathematical Library Functions 128 Focus on Debugging: Hand Tracing a Program 133 Focus on Problem Solving: A Case Study 135 Review Questions and Exercises 140 Programming Challenges 146 Making Decisions 153 Relational Operators 153 The if Statement 158 Expanding the if Statement 166 The if/else Statement 170 Nested if Statements 173 The if/else if Statement 180 The if Statement with Initialization 185 Flags 187 Logical Operators 188 Checking Numeric Ranges with Logical Operators 195 Menus 196 Focus on Software Engineering: Validating User Input 199 Comparing Characters and Strings 201 The Conditional Operator 205 The switch Statement 208 The switch Statement with Initialization 217 More about Blocks and Variable Scope 218 Review Questions and Exercises 222 Programming Challenges 227 Loops and Files 237 The Increment and Decrement Operators 237 Introduction to Loops: The while Loop 242 Using the while Loop for Input Validation 249 Counters 251 The do-while Loop 252 The for Loop 257 Keeping a Running Total 267 Sentinels 270 Focus on Software Engineering: Deciding Which Loop to Use 271 Nested Loops 272 Using Files for Data Storage 275 Optional Topics: Breaking and Continuing a Loop 294 Review Questions and Exercises 296 Programming Challenges 301
Contents
CHAPTER 6 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 6.15 6.16
CHAPTER 7 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 7.11
CHAPTER 8 8.1 8.2 8.3 8.4 8.5
CHAPTER 9 9.1 9.2 9.3 9.4
Functions
309
Focus on Software Engineering: Modular Programming 309 Defining and Calling Functions 310 Function Prototypes 319 Sending Data into a Function 321 Passing Data by Value 326 Focus on Software Engineering: Using Functions in a Menu-Driven Program 328 The return Statement 332 Returning a Value from a Function 334 Returning a Boolean Value 342 Local and Global Variables 344 Static Local Variables 352 Default Arguments 355 Using Reference Variables as Parameters 358 Overloading Functions 365 The exit() Function 369 Stubs and Drivers 372 Review Questions and Exercises 374 Programming Challenges 377 Arrays and Vectors 387 Arrays Hold Multiple Values 387 Accessing Array Elements 389 No Bounds Checking in C++ 401 The Range-Based for Loop 404 Processing Array Contents 408 Focus on Software Engineering: Using Parallel Arrays 417 Arrays as Function Arguments 420 Two-Dimensional Arrays 431 Arrays with Three or More Dimensions 438 Focus on Problem Solving and Program Design: A Case Study 440 Introduction to the STL vector 442 Review Questions and Exercises 456 Programming Challenges 461 Searching and Sorting Arrays 471 Focus on Software Engineering: Introduction to Search Algorithms 471 Focus on Problem Solving and Program Design: A Case Study 477 Focus on Software Engineering: Introduction to Sorting Algorithms 484 Focus on Problem Solving and Program Design: A Case Study 494 Sorting and Searching vectors (Continued from Section 7.11) 503 Review Questions and Exercises 506 Programming Challenges 507 Pointers
511
Getting the Address of a Variable 511 Pointer Variables 513 The Relationship between Arrays and Pointers 520 Pointer Arithmetic 525
ix
x
Contents
9.5 9.6 9.7 9.8 9.9 9.10 9.11
CHAPTER 10 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8
CHAPTER 11 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 11.10 11.11 11.12
CHAPTER 12 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9
Initializing Pointers 527 Comparing Pointers 528 Pointers as Function Parameters 530 Dynamic Memory Allocation 540 Returning Pointers from Functions 544 Using Smart Pointers to Avoid Memory Leaks 550 Focus on Problem Solving and Program Design: A Case Study 553 Review Questions and Exercises 559 Programming Challenges 562 Characters, C-Strings, and More about the string Class
565
Character Testing 565 Character Case Conversion 569 C-Strings 572 Library Functions for Working with C-Strings 576 String/Numeric Conversion Functions 587 Focus on Software Engineering: Writing Your Own C-String-Handling Functions 593 More about the C++ string Class 599 Focus on Problem Solving and Program Design: A Case Study 611 Review Questions and Exercises 613 Programming Challenges 616 Structured Data
621
Abstract Data Types 621 Structures 623 Accessing Structure Members 626 Initializing a Structure 630 Arrays of Structures 633 Focus on Software Engineering: Nested Structures 635 Structures as Function Arguments 639 Returning a Structure from a Function 642 Using Structured Binding Declarations with Structures 645 Pointers to Structures 647 Focus on Software Engineering: When to Use ., When to Use −>, and When to Use * 651 Enumerated Data Types 653 Review Questions and Exercises 664 Programming Challenges 670 Advanced File Operations 675 File Operations 675 File Output Formatting 681 Passing File Stream Objects to Functions 683 More Detailed Error Testing 685 Member Functions for Reading and Writing Files 688 Focus on Software Engineering: Working with Multiple Files 696 Binary Files 698 Creating Records with Structures 703 Random-Access Files 707
Contents
12.10 12.11
CHAPTER 13 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 13.10 13.11 13.12 13.13 13.14 13.15 13.16
CHAPTER 14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 14.10
CHAPTER 15 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8
Opening a File for Both Input and Output 715 Working with the File System 720 Review Questions and Exercises 741 Programming Challenges 745 Introduction to Classes 751 Procedural and Object-Oriented Programming 751 Introduction to Classes 758 Defining an Instance of a Class 763 Why Have Private Members? 776 Focus on Software Engineering: Separating Class Specification from Implementation 777 Inline Member Functions 783 Constructors 786 Passing Arguments to Constructors 791 Destructors 799 Overloading Constructors 803 Private Member Functions 807 Arrays of Objects 809 Focus on Problem Solving and Program Design: An OOP Case Study 813 Focus on Object-Oriented Programming: Simulating Dice with Objects 820 Focus on Object-Oriented Design: The Unified Modeling Language (UML) 824 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 826 Review Questions and Exercises 835 Programming Challenges 840 More about Classes 849 Instance and Static Members 849 Friends of Classes 857 Memberwise Assignment 862 Copy Constructors 863 Operator Overloading 869 Object Conversion 896 Aggregation 898 Focus on Object-Oriented Design: Class Collaborations 903 Focus on Object-Oriented Programming: Simulating the Game of Cho-Han 908 Rvalue References and Move Semantics 918 Review Questions and Exercises 929 Programming Challenges 934 Inheritance, Polymorphism, and Virtual Functions 941 What Is Inheritance? 941 Protected Members and Class Access 950 Constructors and Destructors in Base and Derived Classes 956 Redefining Base Class Functions 970 Class Hierarchies 975 Polymorphism and Virtual Member Functions 981 Abstract Base Classes and Pure Virtual Functions 997 Multiple Inheritance 1004
xi
xii
Contents
Review Questions and Exercises 1011 Programming Challenges 1015 CHAPTER 16 16.1 16.2 16.3 16.4
CHAPTER 17 17.1 17.2 17.3 17.4 17.5 17.6 17.7 17.8
CHAPTER 18 18.1 18.2 18.3 18.4 18.5
CHAPTER 19 19.1 19.2 19.3 19.4 19.5 19.6
CHAPTER 20 20.1 20.2 20.3 20.4
Exceptions and Templates 1023 Exceptions 1023 Function Templates 1043 Focus on Software Engineering: Where to Start When Defining Templates 1049 Class Templates 1050 Review Questions and Exercises 1059 Programming Challenges 1062 The Standard Template Library 1065 Introduction to the Standard Template Library 1065 STL Container and Iterator Fundamentals 1065 The vector Class 1076 The map, multimap, and unordered_map Classes 1090 The set, multiset, and unordered_set Classes 1117 The tuple Class 1124 Algorithms 1131 Introduction to Function Objects and Lambda Expressions 1153 Review Questions and Exercises 1160 Programming Challenges 1165 Linked Lists 1169 Introduction to the Linked List ADT 1169 Linked List Operations 1171 A Linked List Template 1190 Variations of the Linked List 1201 The STL list and forward_list Containers Review Questions and Exercises 1207 Programming Challenges 1209
1202
Stacks and Queues 1213 Introduction to the Stack ADT 1213 Dynamic Stacks 1231 The STL stack Container 1241 Introduction to the Queue ADT 1243 Dynamic Queues 1256 The STL deque and queue Containers 1263 Review Questions and Exercises 1266 Programming Challenges 1268 Recursion
1271
Introduction to Recursion 1271 Solving Problems with Recursion 1275 Focus on Problem Solving and Program Design: The Recursive gcd Function 1283 Focus on Problem Solving and Program Design: Solving Recursively Defined Problems 1284
Contents
20.5 20.6 20.7 20.8 20.9 20.10 20.11
CHAPTER 21 21.1 21.2 21.3
Focus on Problem Solving and Program Design: Recursive Linked List Operations 1285 Focus on Problem Solving and Program Design: A Recursive Binary Search Function 1289 The Towers of Hanoi 1291 Focus on Problem Solving and Program Design: The QuickSort Algorithm 1294 Exhaustive Algorithms 1298 Recursion and Variadic Function Templates 1301 Focus on Software Engineering: Recursion versus Iteration 1303 Review Questions and Exercises 1304 Programming Challenges 1305 Binary Trees 1309 Definition and Applications of Binary Trees 1309 Binary Search Tree Operations 1312 Template Considerations for Binary Search Trees 1329 Review Questions and Exercises 1335 Programming Challenges 1336 Appendix A: The ASCII Character Set 1339 Appendix B: Operator Precedence and Associativity 1341 Quick References 1343 Index 1345 Credit 1363
Online
The following appendices are available at www.pearsonhighered.com/ cs-resources. Appendix C: Introduction to Flowcharting Appendix D: Using UML in Class Design Appendix E: Namespaces Appendix F: Passing Command Line Arguments Appendix G: Binary Numbers and Bitwise Operations Appendix H: STL Algorithms Appendix I: Multi-Source File Programs Appendix J: Stream Member Functions for Formatting Appendix K: Unions Appendix L: Answers to Checkpoints Appendix M: Answers to Odd Numbered Review Questions Case Study 1: C-String Manipulation Case Study 2: High Adventure Travel Agency—Part 1 Case Study 3: Loan Amortization Case Study 4: Creating a String Class Case Study 5: High Adventure Travel Agency—Part 2 Case Study 6: High Adventure Travel Agency—Part 3 Case Study 7: Intersection of Sets Case Study 8: Sales Commission
xiii
LOCATION OF VIDEONOTES IN THE TEXT Chapter 1
Introduction to Flowcharting, p. 20 Designing a Program with Pseudocode, p. 20 Designing the Account Balance Program, p. 25 Predicting the Result of Problem 33, p. 26
Chapter 2
Using cout, p. 32 Variable Definitions, p. 39 Assignment Statements and Simple Math Expressions, p. 64 Solving the Restaurant Bill Problem, p. 83
Chapter 3
Reading Input with cin, p. 87 Formatting Numbers with setprecision, p. 115 Solving the Stadium Seating Problem, p. 146
Chapter 4
The if Statement, p. 158 The if/else Statement, p. 170 The if/else if Statement, p. 180 Solving the Time Calculator Problem, p. 228
Chapter 5
The while Loop, p. 242 The for Loop, p. 257 Reading Data from a File, p. 284 Solving the Calories Burned Problem, p. 301
Chapter 6
Functions and Arguments, p. 321 Value-Returning Functions, p. 334 Solving the Markup Problem, p. 377
Chapter 7
Accessing Array Elements with a Loop, p. 392 Passing an Array to a Function, p. 420 Solving the Chips and Salsa Problem, p. 462
Chapter 8
The Binary Search, p. 474 The Selection Sort, p. 490 Solving the Charge Account Validation Modification Problem, p. 508
Chapter 9
Dynamically Allocating an Array, p. 541 Solving the Pointer Rewrite Problem, p. 563
Chapter 10
Writing a C-String-Handling Function, p. 593 More about the string Class, p. 599 Solving the Backward String Problem, p. 616
LOCATION OF VIDEONOTES IN THE TEXT (continued) Chapter 11
Creating a Structure, p. 623 Passing a Structure to a Function, p. 639 Solving the Weather Statistics Problem, p. 670
Chapter 12
Passing File Stream Objects to Functions, p. 683 Working with Multiple Files, p. 696 Solving the File Encryption Filter Problem, p. 747
Chapter 13
Writing a Class, p. 758 Defining an Instance of a Class, p. 763 Solving the Employee Class Problem, p. 840
Chapter 14
Operator Overloading, p. 869 Class Aggregation, p. 898 Solving the NumDays Problem, p. 935
Chapter 15
Redefining a Base Class Function in a Derived Class, p. 970 Polymorphism, p. 981 Solving the Employee and ProductionWorker Classes Problem, p. 1015
Chapter 16
Throwing an Exception, p. 1024 Handling an Exception, p. 1024 Writing a Function Template, p. 1043 Solving the Exception Project Problem, p. 1063
Chapter 17
The array Container, p. 1068 Iterators, p. 1070 The vector Container, p. 1076 The map Container, p. 1090 The set Container, p. 1117 Function Objects and Lambda Expressions, p. 1153 The Course Information Problem, p. 1165
Chapter 18
Appending a Node to a Linked List, p. 1172 Inserting a Node in a Linked List, p. 1179 Deleting a Node from a Linked List, p. 1185 Solving the Member Insertion by Position Problem, p. 1210
Chapter 19
Storing Objects in an STL stack, p. 1241 Storing Objects in an STL queue, p. 1265 Solving the File Compare Problem, p. 1270
Chapter 20
Reducing a Problem with Recursion, p. 1276 Solving the Recursive Multiplication Problem, p. 1306
Chapter 21
Inserting a Node in a Binary Tree, p. 1314 Deleting a Node from a Binary Tree, p. 1320 Solving the Node Counter Problem, p. 1336
This page intentionally left blank
Preface Welcome to Starting Out with C++: From Control Structures through Objects, 10th edition. This book is intended for use in a two-semester C++ programming sequence, or an accelerated one-semester 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.
Revel If you are using this textbook along with Revel for Gaddis Starting Out with C++, 10e, please understand that there may be some pedagogical differences between the two. Revel, Pearson’s fully immersive, all-in-one digital learning environment, is design for interactive online learning. Therefore, some of the learning aids in the textbook had to be removed or re-imagined in order to create a better online learning experience for students.
Changes in the Tenth Edition This book’s pedagogy, organization, and clear writing style remain the same as in the previous edition. Many improvements and updates have been made, which are summarized here: • New material on the if statement and the switch statement with Initialization C++ 17 introduced new forms of the if statement and the switch statement that include an initialization clause. In this edition, Chapter 4 includes new material on this syntax and shows examples using both. • New Random Number Generator Modern C++ provides a new and improved random number generator with an intuitive syntax for getting a random number within a specified range. This edition replaces the previous C-style technique for random number generation with the new, modern C++ approach. • Tuples Chapter 17, which covers the Standard Template Library, provides a new section on the tuple library. Tuples are explained and numerous examples of using tuples to store and
retrieve data are given.
xvii
xviii
Preface
• New Forms of String and Numeric Literals This edition introduces raw string literals, binary literals, and the use of digit separators in numeric literals. • The filesystem Library Chapter 12 includes a new section on the filesystem library, which was introduced in C++ 17. The filesystem library allows you to work with files and directories at the operating system level, performing operations such as copying and deleting files, getting a list of a directory’s contents, and recursively traversing a directory tree. • Structured Binding Declarations Structured binding declarations, which were introduced in C++ 17, provide a concise syntax for unpacking a collection or data structure and assigning its contents to individual variables. This edition shows how to use structured binding declarations to unpack arrays, structures, and tuples. • Defaulted and Deleted Operations Chapter 14 shows how to use the default and delete key words to explicitly instruct the compiler to either generate or not generate a class’s default constructor, default copy constructor, default move constructor, default copy assignment operator, and default destructor. • Usage of typename Instead of class In Templates In the code for function and class templates, this edition uses the typename key word instead of the class key word for declaring type parameters. • The noexcept Key Word Chapter 16 in this edition introduces the noexcept key word and discusses its use for declaring functions that do not throw an exception. • Enhanced Discussion of Deleting Nodes in a Linked List Chapter 18’s explanation of deleting a node in a linked list has been expanded with more detail, including a new figure that illustrates the process of unlinking a node, and pseudocode describing the process for deleting a node in either a sorted or an unsorted linked list. • Variadic Function Templates Chapter 20 presents a new section on variadic function templates, which allow you to write a set of function templates that use recursion to process a variable number of arguments.
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, some flexibility is provided. The diagram shown in Figure P-1 suggests possible sequences of instruction. Chapter 1 covers fundamental hardware, software, and programming concepts. You may choose to skip this chapter if the class is already familiar with those topics. Chapters 2 through 7 cover basic C++ syntax, data types, expressions, selection structures, repetition structures, functions, and arrays. Each of these chapters builds on the previous chapter and should be covered in the order presented.
Preface
Figure P-1
Chapter dependency chart Chapter 1 Introduction
Chapters 2–7 Basic Language Elements
Chapter 8 Searching and Sorting Arrays
Chapter 10 Characters, C-Strings, and More about the string Class
Chapter 9 Pointers
Chapter 11 Structured Data
Chapter 13 Introduction to Classes
Chapter 14 More about Classes
Chapter 15 Inheritance, Polymorphism, and Virtual Functions
Chapter 16 Exceptions and Templates
Chapter 17 The Standard Template Library
Chapter 18 Linked Lists
Chapter 19 Stacks and Queues
Chapter 20 Recursion
Chapter 21 Binary Trees
Chapter 12 Advanced File Operations
xix
xx
Preface
After Chapter 7 has been covered, you may proceed to Chapter 8, or jump to Chapter 9. After Chapter 9 has been covered, Chapter 10, 11, 12 or 13 may be covered. (If you jump to Chapter 12 at this point, you will need to postpone Sections 12.8, 12.9, and 12.10 until Chapter 11 has been covered.) After Chapter 13, you may cover Chapters 14 through 18 in sequence. Next, you can proceed to either Chapter 19 or Chapter 20. Finally, Chapter 21 may be covered. This text’s approach starts with a firm foundation in structured, procedural programming before delving fully into object-oriented programming and advanced data structures.
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 programming, problem solving, and software design. The components of programs, such as key words, variables, operators, and punctuation, are covered. The tools of the trade, such as pseudocode, flow charts, and hierarchy charts, are also presented. Chapter 2: Introduction to C++ This chapter gets the student started in C++ by introducing data types, identifiers, variable declarations, constants, comments, program output, simple arithmetic operations, and C-strings. Programming style conventions are introduced and good programming style is modeled here, as it is throughout the text. 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 in greater detail, with emphasis on operator precedence. Debugging is introduced, with a section on hand tracing a program. Sections are also included on simple output formatting, on data type conversion and type casting, and on using library functions that work with numbers. Chapter 4: Making Decisions Here, the student learns about relational operators, relational expressions, and how to control the flow of a program with the if, if/else, and if/else if statements. The conditional operator and the switch statement are also covered. Crucial applications of these constructs are covered, such as menu-driven programs and the validation of input. Chapter 5: Loops and Files This chapter covers repetition control structures. The while loop, do-while loop, and for loop are taught, along with common uses for these devices. Counters, accumulators, running totals, sentinels, and other application-related topics are discussed. Sequential file I/O is also introduced. The student learns to read and write text files, and use loops to process the data in a file. Chapter 6: Functions In this chapter, the student learns how and why to modularize programs, using both void and value returning functions. Argument passing is covered, with emphasis on when arguments should be passed by value versus when they need to be passed by reference. Scope of
Preface
variables is covered, and sections are provided on local versus global variables and on static local variables. Overloaded functions are also introduced and demonstrated. Chapter 7: Arrays and Vectors In this chapter, the student learns to create and work with single and multi-dimensional arrays. Many examples of array processing are provided including examples illustrating how to find the sum, average, highest, and lowest values in an array, and how to sum the rows, columns, and all elements of a two-dimensional array. 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. STL vectors are introduced and compared to arrays. Chapter 8: Searching and Sorting Arrays Here, the student learns the basics of sorting arrays and searching for data stored in them. The chapter covers the Bubble Sort, Selection Sort, Linear Search, and Binary Search algorithms. There is also a section on sorting and searching STL vector objects. Chapter 9: Pointers This chapter explains how to use pointers. Pointers are compared to and contrasted with reference variables. Other topics include pointer arithmetic, initialization of pointers, relational comparison of pointers, pointers and arrays, pointers and functions, dynamic memory allocation, and more. Chapter 10: Characters, C-Strings, and More about the string Class This chapter discusses various ways to process text at a detailed level. Library functions for testing and manipulating characters are introduced. C-strings are discussed, and the technique of storing C-strings in char arrays is covered. An extensive discussion of the string class methods is also given. Chapter 11: Structured Data The student is introduced to abstract data types and taught how to create them using structures, unions, and enumerated data types. Discussions and examples include using pointers to structures, passing structures to functions, and returning structures from functions. Chapter 12: Advanced File Operations This chapter covers sequential access, random access, text, and binary files. The various modes for opening files are discussed, as well as the many methods for reading and writing file contents. Advanced output formatting is also covered. The chapter includes a discussion of operating system paths and introduces the standard filesystem library for accessing files and directories at the operating system level. Chapter 13: Introduction to Classes The student now shifts focus to the object-oriented paradigm. This chapter covers the fundamental concepts of classes. Member variables and functions are discussed. The student learns about private and public access specifications, and reasons to use each. The topics of constructors, overloaded constructors, and destructors are also presented. The chapter presents a section modeling classes with UML, and how to find the classes in a particular problem.
xxi
xxii
Preface
Chapter 14: More about Classes This chapter continues the study of classes. Static members, friends, memberwise assignment, and copy constructors are discussed. The chapter also includes in-depth sections on operator overloading, object conversion, and object aggregation. There is also a section on class collaborations and the use of CRC cards. Chapter 15: Inheritance, Polymorphism, and Virtual Functions The study of classes continues in this chapter with the subjects of inheritance, polymorphism, and virtual member functions. The topics covered include base and derived class constructors and destructors, virtual member functions, base class pointers, static and dynamic binding, multiple inheritance, and class hierarchies. Chapter 16: Exceptions and Templates The student learns to develop enhanced error trapping techniques using exceptions. Discussion then turns to function and class templates as a method for reusing code. Chapter 17: The Standard Template Library This chapter discusses the containers, iterators, and algorithms in the Standard Template Library (STL). The specific containers covered are the array, vector, map, multimap, unordered_map, set, multiset, unordered_set, and tuple classes. The student then learns about sorting, searching, permutation, and set algorithms. The chapter concludes with a discussion of function objects (functors) and lambda functions. Chapter 18: Linked Lists This chapter introduces concepts and techniques needed to work with lists. A linked list ADT is developed and the student is taught to code operations such as creating a linked list, appending a node, traversing the list, searching for a node, inserting a node, deleting a node, and destroying a list. A linked list class template is also demonstrated. Chapter 19: 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. Chapter 20: Recursion This chapter discusses recursion and its use in problem solving. A visual trace of recursive calls is provided, and recursive applications are discussed. Many recursive algorithms are presented, including recursive functions for finding factorials, finding a greatest common denominator (GCD), performing a binary search, and sorting (QuickSort). The classic Towers of Hanoi example is also presented. For students who need more challenge, there is a section on exhaustive algorithms. The chapter concludes with a discussion of variadic function templates, which use recursion to process a variable number of arguments. Chapter 21: Binary Trees This chapter covers the binary tree ADT and demonstrates many binary tree operations. The student learns to traverse a tree, insert an element, delete an element, replace an element, test for an element, and destroy a tree.
Preface
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 chart showing the C++ operators and their precedence. The following appendices are available online at www.pearsonhighered.com/cs-resources. Appendix C: Introduction to Flowcharting A brief introduction to flowcharting. This tutorial discusses sequence, decision, case, repetition, and module structures. Appendix D: Using UML in Class Design This appendix shows the student how to use the Unified Modeling Language to design classes. Notation for showing access specification, data types, parameters, return values, overloaded functions, composition, and inheritance are included. Appendix E: Namespaces This appendix explains namespaces and their purpose. Examples showing how to define a namespace and access its members are given. Appendix F: Passing Command Line Arguments Teaches the student how to write a C++ program that accepts arguments from the command line. This appendix will be useful to students working in a command line environment, such as Unix, Linux, or the Windows command prompt. Appendix G: Binary Numbers and Bitwise Operations A guide to the C++ bitwise operators, as well as a tutorial on the internal storage of integers Appendix H: STL Algorithms This appendix gives a summary of each of the function templates provided by the Standard Template Library (STL), and defined in the header file. Appendix I: Multi-Source File Programs Provides a tutorial on creating programs that consist of multiple source files. Function header files, class specification files, and class implementation files are discussed. Appendix J: Stream Member Functions for Formatting Covers stream member functions for formatting such as setf Appendix K: Unions This appendix introduces unions. It describes the purpose of unions and the difference between a union and a struct, demonstrates how to declare a union and define a union variable, and shows example programs that use unions.
xxiii
xxiv
Preface
Appendix L: Answers to Checkpoints Students may test their own progress by comparing their answers to the Checkpoint exercises against this appendix. The answers to all Checkpoints are included. Appendix M: Answers to Odd Numbered Review Questions Another tool that students can use to gauge their progress.
Features of the Text Concept Statements
Each major section of the text starts with a concept statement. This statement summarizes the ideas of the section.
Example Programs
The text has hundreds of 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.
In the Spotlight
Each of these sections provides a programming problem and a detailed, step-by-step analysis showing the student how to solve it.
VideoNotes
Videos that provide explanations of specific topics and show the student how to solve various programming problems are available for viewing at www.pearsonhighered.com/cs-resources. Icons appear throughout the text alerting the student to specific videos.
Checkpoints
Checkpoints are questions placed throughout each chapter as a self-test study aid. These questions allow students to check how well they have learned a new topic. Answers for all Checkpoint questions can be downloaded from the book’s companion Web site at www. pearsonhighered.com/cs-resources.
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 are notes that 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. These case studies are designed to highlight the major topics of the chapter in which they appear.
Preface
Review Questions and Exercises
Each chapter presents a thorough and diverse set of review questions, such as fill-in-the-blank and short answer, that check the student’s mastery of the basic 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. Answers to the odd-numbered review questions and review exercises can be downloaded from the book’s companion Web site at www.pearsonhighered.com/cs-resources.
Programming Challenges
Each chapter offers a pool of programming exercises designed to solidify the student’s knowledge of the topics currently being studied. In most cases, the assignments present real-world problems to be solved. When applicable, these exercises include input validation rules.
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 team work within the classroom.
Modern C++
Throughout the text, new Modern C++ language features are introduced.
Supplements Student Online Resources Many student resources are available for this book from the publisher. The following items are available on the Gaddis Series Companion Web site at www.pearsonhighered.com/ cs-resources: ●
The source code for each example program in the book
●
Access to the book’s VideoNotes
●
●
A full set of appendices, including answers to the Checkpoint questions and answers to the odd-numbered review questions A collection of valuable Case Studies
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
xxv
xxvi
Contents ●
Computerized test bank
●
Answers to all Student Lab Manual questions
●
Solutions for all Student Lab Manual programs
Visit the Gaddis Series Companion Web site at www.pearsonhighered.com/cs-resources to access the Instructor Resources. If you do not already have access to the Pearson IRC, please contact your Pearson representative at Pearson.com/RepLocator.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++: From Control Structures through Objects
●
Starting Out with C++: Early Objects
●
Starting Out with C++: Brief Version
The following chart will help you determine which book is right for your course.
Contents ■ F ROM
CONTROL STRUCTURES THROUGH OBJECTS ■ B RIEF VERSION
■ E ARLY
OBJECTS
LATE INTRODUCTION OF OBJECTS
EARLIER INTRODUCTION OF OBJECTS
Classes are introduced in Chapter 13 of the standard text and the brief text, after control structures, functions, arrays, and pointers. Advanced OOP topics, such as inheritance and polymorphism, are covered in the following two chapters.
Classes are introduced in Chapter 7, after control structures and functions, but before arrays and pointers. Their use is then integrated into the remainder of the text. Advanced OOP topics, such as inheritance and polymorphism, are covered in Chapters 11 and 15.
INTRODUCTION OF DATA STRUCTURES AND RECURSION
INTRODUCTION OF DATA STRUCTURES AND RECURSION
Linked lists, stacks and queues, and binary trees are Linked lists, stacks and queues, and binary introduced in the final chapters of the standard text. trees are introduced in the final chapters of the text, after the chapter on recursion. Recursion is covered after stacks and queues, but before binary trees. These topics are not covered in the brief text, though it does have appendices dealing with linked lists and recursion.
xxvii
xxviii Preface
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. Ahmad Abuhejleh University of Wisconsin–River Falls
C.C. Chao Jacksonville State University
David Akins El Camino College
Joseph Chao Bowling Green State University
Steve Allan Utah State University
Royce Curtis Western Wisconsin Technical College
Vicki Allan Utah State University
Joseph DeLibero Arizona State University
Karen M. Arlien Bismark State College
Michael Dixon Sacramento City College
Mary Astone Troy University
Jeanne Douglas University of Vermont
Ijaz A. Awan Savannah State University
Michael Dowell Augusta State University
Robert Baird Salt Lake Community College
Qiang Duan Penn State University—Abington
Don Biggerstaff Fayetteville Technical Community College
William E. Duncan Louisiana State University
Michael Bolton Northeastern Oklahoma State University
Daniel Edwards Ohlone College
Bill Brown Pikes Peak Community College
Judy Etchison Southern Methodist University
Robert Burn Diablo Valley College
Dennis Fairclough Utah Valley State College
Charles Cadenhead Richland Community College
Xisheng Fang Ohlone College
Randall Campbell Morningside College
Mark Fienup University of Northern Iowa
Wayne Caruolo Red Rocks Community College
Richard Flint North Central College
Cathi Chambley-Miller Aiken Technical College
Ann Ford Tyson Florida State University
Chia-Chin Chang Lakeland College
Jeanette Gibbons South Dakota State University
Preface
James Gifford University of Wisconsin–Stevens Point
Sheila Lancaster Gadsden State Community College
Leon Gleiberman Touro College
Ray Larson Inver Hills Community College
Barbara Guillott Louisiana State University
Michelle Levine Broward College
Pranshu Gupta DeSales University
Jennifer Li Ohlone College
Ranette Halverson, Ph.D. Midwestern State University
Norman H. Liebling San Jacinto College
Ken Hang Green River Community College
Cindy Lindstrom Lakeland College
Carol Hannahs University of Kentucky
Zhu-qu Lu University of Maine, Presque Isle
Charles Hardnett Gwinnett Technical College
Heidar Malki University of Houston
Dennis Heckman Portland Community College
Debbie Mathews J. Sargeant Reynolds Community College
Ric Heishman George Mason University
Svetlana Marzelli Atlantic Cape Community College
Michael Hennessy University of Oregon
Rick Matzen Northeastern State University
Ilga Higbee Black Hawk College
Robert McDonald East Stroudsburg University
Patricia Hines Brookdale Community College
James McGuffee Austin Community College
Mike Holland Northern Virginia Community College
Jie Meichsner St. Cloud State University
Mary Hovik Lehigh Carbon Community College
Dean Mellas Cerritos College
Richard Hull Lenoir-Rhyne College
Lisa Milkowski Milwaukee School of Engineering
Kay Johnson Community College of Rhode Island
Marguerite Nedreberg Youngstown State University
Chris Kardaras North Central College
Lynne O’Hanlon Los Angeles Pierce College
Willard Keeling Blue Ridge Community College
Frank Paiano Southwestern Community College
A.J. Krygeris Houston Community College
Theresa Park Texas State Technical College
xxix
xxx
Preface
Mark Parker Shoreline Community College
Richard Snyder Lehigh Carbon Community College
Ron Del Porto Penn State Erie, The Behrend College
Donald Southwell Delta College
Tino Posillico SUNY Farmingdale Frederick Pratter Eastern Oregon University Susan L. Quick Penn State University Alberto Ramon Diablo Valley College Bazlur Rasheed Sault College of Applied Arts and Technology
Caroline St. Claire North Central College Kirk Stephens Southwestern Community College Cherie Stevens South Florida Community College Dale Suggs Campbell University Mark Swanson Red Wing Technical College Ann Sudell Thorn Del Mar College
Farshad Ravanshad Bergen Community College
Martha Tillman College of San Mateo
Susan Reeder Seattle University
Ralph Tomlinson Iowa State University
Sandra Roberts Snead College
David Topham Ohlone College
Lopa Roychoudhuri Angelo State University
Robert Tureman Paul D. Camp Community College
Lisa Rudnitsky Baruch College
Arisa K. Ude Richland College
Dolly Samson Weber State University
Peter van der Goes Rose State College
Ruth Sapir SUNY Farmingdale
Stewart Venit California State University, Los Angeles
Jason Schatz City College of San Francisco
Judy Walters North Central College
Dr. Sung Shin South Dakota State University
John H. Whipple Northampton Community College
Bari Siddique University of Texas at Brownsville
Aurelia Williams Norfolk State University
William Slater Collin County Community College
Chadd Williams Pacific University
Shep Smithline University of Minnesota
Vida Winans Illinois Institute of Technology
Preface
I would like to thank the faculty, staff, and administration at Haywood Community College for the opportunity to build a career teaching the subjects that I love. I would also like to thank my family and friends for their support in all of my projects. It is a great honor to be published by Pearson, and I am extremely fortunate to have Tracy Johnson as my Content Manager. She and her colleagues Holly Stark, Erin Sullivan, Alicia Wilson, Rachel Reeve, Scott Disanno, Bob Engelhardt, Timothy Gardiner, and Carol Snyder have worked tirelessly to produce and promote this book. Thanks to you all!
About the Author Tony Gaddis is the principal author of the Starting Out with series of textbooks. He has two decades of experience teaching computer science courses, primarily at Haywood Community College. Tony is a highly acclaimed instructor who 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, Alice, C++, Java™, Microsoft® Visual Basic®, Microsoft® Visual C#, Python, and App Inventor, all published by Pearson.
xxxi
This page intentionally left blank
CHAPTER
1
Introduction to Computers and Programming
TOPICS 1.1 1.2 1.3
1.1
Why Program? Computer Systems: Hardware and Software Programs and Programming Languages
1.4 1.5 1.6 1.7
What Is a Program Made of? Input, Processing, and Output The Programming Process Procedural and Object-Oriented Programming
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 conduct business transactions, communicate with customers and coworkers, analyze data, make presentations, control machines in manufacturing facilities, and many many other tasks. At home, people use computers for tasks such as paying bills, shopping online, social networking, and playing computer games. And don’t forget that smartphones, MP3 players, DVRs, 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 computers are not designed to do just one job, but 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. 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 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, academia, entertainment, and almost every other field. 1
2
Chapter 1
Introduction to Computers and Programming
Figure 1-1
A word processing program and a presentation program
Computer programming is both an art and a science. It is an art because every aspect of a program should be carefully designed. 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” Documentation, help files, tutorials, and so on
There is also a scientific, or engineering, side to programming. Because programs rarely work right the first time they are written, a lot of testing, correction, and redesigning is required. This demands patience and persistence from 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 make 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 CONCEPT: All computer systems consist of similar hardware devices and software components. This section provides an overview of standard computer hardware and software organization.
1.2 Computer Systems: Hardware and Software
Hardware Hardware refers to the physical components of which a computer is made. 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 Secondary storage devices Input devices Output devices
The organization of a computer system is depicted in Figure 1-2. Typical devices in a computer system
Nikita Rogul/ Shutterstock
Chiyacat/ Shutterstock
Input Devices
Output Devices
Peter Guess/ Shutterstock
Feng Yu/Shutterstock
Iko/Shutterstock
Aquila/ Shutterstock
Central Processing Unit
Art gallery/ Shutterstock
Figure 1-2
Jocic/Shutterstock
Elkostas/Shutterstock
Main Memory (RAM) Tkemot/Shutterstock
Secondary Storage Devices
StockPhotosArt/Shutterstock
Kastianz/Shutterstock
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. Figure 1-3 shows such a device. The two women in
3
4
Chapter 1
Introduction to Computers and Programming
Figure 1-3
The ENIAC computer
U.S. Army Center of Military History
the photo are working with the historic ENIAC computer. The ENIAC, considered by many to be the world’s first programmable electronic computer, was built in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab technician holding a modern-day microprocessor. In addition to being much smaller than the old electromechanical CPUs in early computers, microprocessors are also much more powerful. Figure 1-4
A microprocessor
Creativa/Shutterstock
1.2 Computer Systems: Hardware and Software
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 CPU’s operations. It is responsible for determining where to get the next instruction and 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-5. Figure 1-5
Organization of a CPU Central Processing Unit Arithmetic and Logic Unit Instruction (Input)
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 component to perform an operation.
These steps are repeated as long as there are instructions to perform.
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 with which the program is working. 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 RAM. 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 locations known as bytes. One byte is enough memory to store only a letter of the alphabet or a small number. In order to do
5
6
Chapter 1
Introduction to Computers and Programming
anything meaningful, a computer must have lots of bytes. Most computers today have 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. Figure 1-6 shows a group of memory cells with their addresses. In the illustration, sample data is stored in memory. The number 149 is stored in the cell with the address 16, and the number 72 is stored at address 23.
Figure 1-6
Memory
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. Programs are normally stored in secondary memory and loaded into main memory as needed. Important data such as word processing documents, payroll data, and inventory records is saved to secondary storage as well. The most common type of secondary storage device is the disk drive. A traditional disk drive stores data by magnetically encoding it onto a circular disk. Solid-state drives, which store data in solid-state memory, are increasingly becoming popular. A solid-state drive has no moving parts and operates faster than a traditional disk drive. Most computers have some sort of secondary storage device, either a traditional disk drive or a solid-state drive, mounted inside their case. External storage devices can be used to create backup copies of important data or to move data to another computer. For example, USB (Universal Serial Bus) drives and SD (Secure Digital) memory cards are small devices that appear in the system as disk drives. They are inexpensive, reliable, and small enough to be carried in your pocket.
Input Devices Input is any data 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, touchscreen, scanner, digital camera, and
1.2 Computer Systems: Hardware and Software
microphone. Disk drives, CD/DVD drives, and USB drives can also be considered input devices because programs and information are 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 screens, printers, and speakers. Storage devices can also be considered output devices because the CPU sends them data to be saved.
Software If a computer is to function, software is not optional. Everything 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: • 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 will 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. 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.
7
8
Chapter 1
Introduction to Computers and Programming
Checkpoint
1.3
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 control 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?
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 should 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 well-defined steps for performing a task or solving a problem. Notice these steps are sequentially ordered. Step 1 should be performed before Step 2, and so forth. It is important that these instructions be performed in their proper sequence. Although you and I might easily understand the instructions in the pay-calculating algorithm, it is not ready to be executed on a computer. A computer’s CPU can only process
1.3 Programs and Programming Languages
instructions that are written in machine language. If you were to look at a machine language program, you would see a stream of binary numbers (numbers consisting of only 1s and 0s). The binary numbers form machine language instructions, which the CPU interprets as commands. Here is an example of what a machine language instruction might look like: 1011010000000101
As you can imagine, the process of encoding an algorithm in machine language is very tedious and difficult. In addition, each different type of CPU has its own machine language. If you wrote a machine language program for computer A then wanted to run it on computer B, which 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 than machine language. Programmers save their programs in text files, then use special software to convert their programs to machine language. Program 1-1 shows how the pay-calculating algorithm might be written in C++. The “Program Output with Example Input” shows what the program will display on the screen when it is running. In the example, the user enters 10 for the number of hours worked and 15 for the hourly pay rate. The program displays the earnings, which are $150.
NOTE: The line numbers that are 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
// 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; (program continues)
9
10
Chapter 1
Introduction to Computers and Programming
Program 1-1 19 20 21 22 23
(continued)
// Display the pay. cout > letter; cout sold; store2 −= sold; // Adjust store 2's inventory. // Get the number of widgets sold at store 3. cout > sold; store3 −= sold; // Adjust store 3's inventory. // Display each store's current inventory. cout number; // Get the length kitchen.setLength(number); // Store in kitchen object cout > number; // Get the width kitchen.setWidth(number); // Store in kitchen object // Get the bedroom dimensions. cout > number; // Get the length bedroom.setLength(number); // Store in bedroom object cout > number; // Get the width bedroom.setWidth(number); // Store in bedroom object // Get the den dimensions. cout > number; den.setLength(number); cout > number; den.setWidth(number);
// Get the length // Store in den object // Get the width // Store in den object
// Calculate the total area of the three rooms. totalArea = kitchen.getArea() + bedroom.getArea() + den.getArea(); // Display the total area of the three rooms. cout setLength(4.8);
The first statement calls the setWidth member function, passing 12.5 as an argument. Because rectPtr points to the myRectangle object, this will cause 12.5 to be stored in the myRectangle object’s width variable. The second statement calls the setLength member function, passing 4.8 as an argument. This will cause 4.8 to be stored in the myRectangle
13.3 Defining an Instance of a Class
object’s length variable. Figure 13-11 shows the state of the myRectangle object after these statements have executed. Figure 13-11 State of the myRectangle object The rectPtr pointer variable holds the address of the myRectangle object
The myRectangle object
address
width: 12.5 length: 4.8
Class object pointers can be used to dynamically allocate objects. The following code shows an example: 1 2 3 4 5 6 7 8 9 10 11 12 13
// Define a Rectangle pointer. Rectangle *rectPtr = nullptr; // Dynamically allocate a Rectangle object. rectPtr = new Rectangle; // Store values in the object's width and length. rectPtr−>setWidth(10.0); rectPtr−>setLength(15.0); // Delete the object from memory. delete rectPtr; rectPtr = nullptr;
Line 2 defines rectPtr as a Rectangle pointer. Line 5 uses the new operator to dynamically allocate a Rectangle object and assign its address to rectPtr. Lines 8 and 9 store values in the dynamically allocated object’s width and length variables. Figure 13-12 shows the state of the dynamically allocated object after these statements have executed. Figure 13-12 rectPtr points to a dynamically allocated Rectangle object The rectPtr pointer variable holds the address of a dynamically allocated Rectangle object address
A Rectangle object width: 10.0 length: 15.0
Line 12 deletes the object from memory, and line 13 stores the address 0 in rectPtr. Recall from Chapter 9 that this prevents code from inadvertently using the pointer to access the area of memory that has been freed. It also prevents errors from occurring if delete is accidentally called on the pointer again. Program 13-3 is a modification of Program 13-2. In this program, kitchen, bedroom, and den are Rectangle pointers. They are used to dynamically allocate Rectangle objects. The output is the same as Program 13-2.
771
772
Chapter 13
Introduction to Classes
Program 13-3 1 2 3 4 5
// This program creates three instances of the Rectangle class. #include using namespace std; // Rectangle class declaration.
Lines 6 through 62 have been left out. 63 64 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
//***************************************************** // Function main * //***************************************************** int main() { double number; double totalArea; Rectangle *kitchen = nullptr; Rectangle *bedroom = nullptr; Rectangle *den = nullptr;
// // // // //
To hold a number The total area To point to kitchen dimensions To point to bedroom dimensions To point to den dimensions
// Dynamically allocate the objects. kitchen = new Rectangle; bedroom = new Rectangle; den = new Rectangle; // Get the kitchen dimensions. cout > number; // Get the length kitchen−>setLength(number); // Store in kitchen object cout > number; // Get the width kitchen−>setWidth(number); // Store in kitchen object // Get the bedroom dimensions. cout > number; // Get the length bedroom−>setLength(number); // Store in bedroom object cout > number; // Get the width bedroom−>setWidth(number); // Store in bedroom object // Get the den dimensions. cout > number; den−>setLength(number); cout > number; den−>setWidth(number);
// Get the length // Store in den object // Get the width // Store in den object
// Calculate the total area of the three rooms.
13.3 Defining an Instance of a Class 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
totalArea = kitchen−>getArea() + bedroom−>getArea() + den−>getArea(); // Display the total area of the three rooms. cout number; // Get the kitchen−>setWidth(number); // Store in
length kitchen object width kitchen object
// Get the bedroom dimensions. cout > number; // Get the length bedroom−>setLength(number); // Store in bedroom object cout > number; // Get the width bedroom−>setWidth(number); // Store in bedroom object // Get the den dimensions. cout > number; den−>setLength(number); cout > number; den−>setWidth(number);
// Get the length // Store in den object // Get the width // Store in den object
// Calculate the total area of the three rooms. totalArea = kitchen−>getArea() + bedroom−>getArea() + den−>getArea();
13.3 Defining an Instance of a Class 107 108 109 110 111 112 113
// Display the total area of the three rooms. cout rectLength; (program continues)
781
782
Chapter 13
Introduction to Classes
Program 13-5 22 23 24 25 26 27 28 29 30 31 32 33
(continued)
// Store the width and length of the rectangle // in the box object. box.setWidth(rectWidth); box.setLength(rectLength); // Display the rectangle's data. cout player1Name; cout > player2Name; // Create the dealer. Dealer dealer; // Create the two players. Player player1(player1Name); Player player2(player2Name); // Play the rounds. for (int round = 0; round < MAX_ROUNDS; round++) { cout length;
16.1 Exceptions 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
// Store the length in the myRectangle object. tryAgain = true; while (tryAgain) { try { myRectangle.setLength(length); // If no exception was thrown, then the // next statement will execute. tryAgain = false; } catch (Rectangle::NegativeLength) { cout > length; } } // Display the area of the rectangle. cout "; cin >> element; } // Get the numbers purchased on a lottery ticket. cout 67 > 88 > 93 Enter your 5 lottery numbers: > 25 > 15 > 62 > 93 > 88 Sorry, you did not win.
Program Output Enter the 5 winning numbers: > 10 > 25 > 67 > 88 > 93 Enter your 5 lottery numbers: > 67 > 10 > 93 > 88 > 25 You won the lottery!
Plugging Your Own Functions into an Algorithm When a C++ program is running, the executable code for each of the functions in that program is stored in memory. You can use the name of a function to get that function’s address in memory, in the same way that you can use the name of an array to get that array’s address in memory. This capability allows you to get a function pointer, which is a pointer to a function’s executable code. Many of the function templates in the STL are designed to accept function pointers as arguments. This allows you to “plug” one of your own functions into the algorithm. For example, here is the general format of the for_each function: for_each(iterator1, iterator2, function)
In the general format, the iterator1 and iterator2 arguments mark the beginning and end of a range of elements. The function argument is the address of a function that accepts an element as its argument (Any value returned from function is ignored). The for_each() function iterates over the range of elements, passing each element as an argument to function.
1137
1138
Chapter 17
The Standard Template Library
Program 17-28 demonstrates the for_each() function. The program defines a function named doubleNumber(). The doubleNumber() function accepts a reference to an int as its argument, and it doubles the value of the argument. The program uses the for_each() function to double the value of every element in a vector of integers. Program 17-28 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include #include #include using namespace std; // Function prototype void doubleNumber(int &); int main() { vector numbers = { 1, 2, 3, 4, 5 }; // Display the numbers before doubling. for (auto element : numbers) cout ), 647–680, 651, 770 ascending order, sorting in, 484 ASCII, 51, 52, 201 assign() member function, string class, 607 assignment combined, 109–111 memberwise, 862–863 multiple, 108 assignment operator (=), 40, 61–62, 108, 165–166, 604 assignment statement, 61 associative containers, 1066 associativity, 95–96, 194–195
at() member function array class, 1069 map class, 1094 string class, 607 vector, 455 atof() library function, 587 atoi() library function, 587 atol() library function, 587
attributes, 752 auto key word, 62–63 to define iterator, 1073 averages in arrays, 412–413 calculating, 99–100
B
back() member function, array class, 1069 bad_alloc exception, 1041–1042 bad() member function, file stream, 686
base case, recursion, 1276 base class, 942 abstract, 997–1001 multiple, 1004–1009 base class access specification, 946–947, 954–955 base class functions, redefining, 970–974 base class pointers, 989–991 BASIC, 11 begin() member function array class, 1069, 1071 map class, 1097–1098 string class, 607 binary digit (bit), 6 binary files, 276, 698–699 binary numbers, 9 binary operators, 65 binary predicate, 1157 binary search, 474–477 efficiency, 477 recursive version, 1271–1274 binary_search() function, 1132–1135 binary trees, 1109, 1309–1310 applications of, 1309–1310 child nodes, 1309 creating, 1313–1314 deleting a node, 1320–1329 described, 1309–1310 inorder traversal, 1316 inserting a node, 1314–1315 leaf nodes, 1309 NULL address, 1309 operations, 1313–1329 postorder traversal, 1316 preorder traversal, 1316 root node, 1309 searching, 1319–1320 searching for a value in, 1295 search trees, 1311 subtrees, 1310 templates for, 1329–1334
Index traversing, 1310–1317 tree pointer, 1309 binding, 982 dynamic, 983 static, 983 bit, 6 blocks, of code, 218–224, 246–247 block scope, 219 blueprints, classes as, 755 body of function, 311, 313 of loop, 243 bool
data type, 59 flag, 187 returning from function, 342–344 Boolean expressions, 59, 154, 399 bounds checking, for arrays, 401–402 braces, 246–247 break statement, 210, 211, 294–296 bubble sort, 484–487 byte, 5–6
C
C, 11 C#, 11 C++, 11 calling a function, 312–319 capacity() member function string class, 607 vector, 455, 1120 capitalization, 44 capture list, 1157 case conversion, character, 569–571 case statement, 209–210 case study Demetris Leadership Center, 478–484, 494–502 dollarFormat function, 611–613 General Crates, Inc., 135–139 Home Software Company, 611–613, 813–820 National Commerce Bank, 440–442 United Cause, 554–559 catch block, 1024 catch key word, 1024 cbegin() member function, array class, 1069, 1074 cend() member function, array class, 1069, 1074 central processing unit (CPU), 3–5 character case conversion, 569–572 tolower function, 570 toupper function, 570 character literals, 50, 52–54 characters, 17, 565–571 character literals, 50, 52–54 comparing, 201–204 converting cases, 569–571 and string objects, 122–128 character testing, 565–569 functions, 567–568 isalnum function, 566
isalpha function, 566 isdigit function, 566 islower function, 566 isprint function, 566 ispunct function, 566 isspace function, 566 isupper function, 566 char data type, 50–54 cin, 18, 87–92
entering multiple values, 89–91 getline() member function, 123, 575, 590–591 get() member function, 124–126 ignore() member function, 127, 591 inputting characters, 124 keyboard buffer, 91 Circle pointer, 650 circularly linked list, 1201 class constructors, 957–961 classes, 751–848, 849–940 abstract base, 997–1001 accessors, 762 access specifiers, 758–759 aggregation, 898–903 arguments to constructors, 791–795 arrays of class objects, 809–810 base, 942 as blueprint, 755 collaborations, 903–906 const member functions, 760, 763 constructor overloading, 803–805 constructors, 786–798, 956–957 conversion of class objects, 896–898 copy constructor, 863–866 data hiding, 763 declaration statements, 758 default constructor, 791, 798 defining class objects, 763–775 derived, 942–943 described, 758 destructors, 799–802, 956–960 dot operator (.), 764 dynamically allocated objects, 761–762, 771–772 finding, 826–834 forward declaration, 859 friend functions, 857–858 getter function, 762 “has a” relationship, 900 hierarchies of, 975–980 Home Software Company case study, 611–612 implementation file, 778 include guard, 778–779 inheritance, 941–950 inline member functions, 783–785 instance members, 849–856 “is a” relationship, 942–949, 981 member functions, defining, 761–762 memberwise assignment, 862–863 multiple inheritance, 1004–1011
1347
1348
Index classes (continued) mutators, 762 objects vs., 751–754 operator overloading, 869–895 overloading member functions, 807 PassFailExam, 978 placement of public and private members, 760–762 pointers, 770–773 polymorphism, 981–997 private member functions, 807–809 private members, 758, 760–761, 776–777 problem domain, 827 and procedural/object-oriented programming, 751–757 protected members and class access, 950–955 public member functions, 962–963 public members, 758, 760–761 redefining base class functions, 970–974 responsibilities of, 826–848 scope resolution operator (::), 762, 799 setter function, 762 specification and implementation, 777–783 stale data, avoiding, 770 static members, 849–856 templates, 1043–1048 and UML, 824–826 virtual functions, 983–987 whole-part relationship, 900 class implementation file, 778 class specification file, 777 class template objects, 1054 class templates, 1050–1053 defining objects of, 1054–1059 and inheritance, 1056–1058 linked list, 1178–1179 type parameter, 1043 clear() member function file stream objects, 686 string class, 607 vector, 452, 455, 1050–1051 C++ library, 565, 569, 572, 754 close() member function, file stream objects, 279 closing of file, 279 cmath header file, 98, 128 COBOL, 11 code reuse, 310 collaborations, class, 903–908 combined assignment operators, 109–111 comments, 27, 72–74 /* */, 73 //, 27 multi-line, 73–74 single-line, 72–73 compare() member function, string class, 605–608 compilers, 12, 675 default operations provided by, 926–929 compound operators, 109 concatenation, 577–578 conditional expression, 205–208 value of, using, 206–207 conditional loop, 257 conditional operator, 205–208
console, 31 console output, 31 const
as array parameter, 425–426 copy constructors, 863–866 member functions, 760, 763 const_iterator, and mutable iterator, 1074 constants, 42 arguments passed to, 791–798 in base and derived classes, 956–967 constructors, 786–789 copy, 863–868 default, 791, 796–798 default arguments with, 796–798 global, 348–350 named, 74–76 overloading, 803–805 pointers to, 533–535 constructors associative, 1066 class, 957–961 delegation, 806–807 derived classes, 956 inheritance, 967–968 sequence, 1066 STL, 442 containers adapter class, 1067 array class, 1067–1069 associative, 1066 definition, 1065 iterators and, 1069 sequence, 1066 continue statement, 295–296 control unit, 5 control variable, 245 conversion object, 896–898 string/numeric, 587–593 copy assignment operator, 873–875 copy constructors, 863–868 const parameters in, 866–868 default, 868 and function parameters, 868 list class, 1203 map class, 1090 set class, 1117 vector class, 1076 copy() member function, string class, 607 count-controlled loops, 257, 265–266 count() member function multimap class, 1112–1113 multiset class, 1123 set class, 1119 counters, 251–252 cout, 18, 31–37, 157 fixed manipulator with, 118–119 left manipulator with, 120–121 right manipulator with, 120–121 setprecision manipulator with, 115–117 setw manipulator with, 113–114 showpoint manipulator with, 119–120
Index count_if() function, 1138–1139 cout statement, 239
C programming language, 10–11, 574 C++ programming language, 10, 11, 22 CPU (central processing unit), 3–5 crbegin() member function, array class, 1069 CRC cards, 907–908 crend() member function, array class, 1069 C++ runtime library, 128 cstdlib header file, 131 cstring header file, 576, 581, 585 C-strings, 572–584 in arrays, 574–576 comparing, 582–584 concatenation, 577–578 copying, 578–579 described, 572–573 filenames as, 294 handling functions, 593–598 length of, 576–577 library functions, 576–586 and null terminators, 573–574 numeric conversion functions, 587–593 searching within, 578–582 strcmp function, 601 and string literals, 573–574 c_str() member function, 294
D
database management systems (DBMS), 675 data hiding, 763 data() member function, array class, 1069 data types abstract, 621–622 bool, 59 char, 50–54 coercion, 102 conversion, 102–103 demotion, 102 double, 56 enumerated, 653–663 float, 56 floating-point, 56–59 generic, 1043 int, 45, 46 integer, 44–49 long, 46 long double, 46 numeric, 45 primitive, 622 promotion, 102 ranking, 102–103 short, 45, 46 size of, determining, 60 string class, 54–55 type casting, 105–108 unsigned int, 45, 46
unsigned long, 45, 46 unsigned short, 45, 46
debugging desk-checking, 21 hand-tracing, 133–135 stubs and drivers, 372–373 decision making, 153–236 blocks and scope, 218–220 checking numeric ranges, 195 comparing characters and strings, 201–202 conditional execution, 166–168 conditional operator, 205–208 flags, 187 if/else if statements, 180–182, 184–185 if/else statements, 170–172 if statement, 158–166 logical operators, 188–195 menus, 196–199 nested if statements, 173–176 relational operators, 153–157 relationship, value of, 154–156 semicolons, 162 switch statement, 208–218 truth, 156–158 validating user input, 199–200 decode, 4 decrement operator (−−), 237–242 in mathematical expressions, 241 postfix and prefix modes, 239–241 in relational expressions, 241–242 default arguments, 355–358, 796–798 default constructors, 791, 798 list class, 1202 map class, 1090 set class, 1117 vector class, 1076 default copy constructor, 868 default statement, 209–210 #define directive, 779 delete operator, 541 Demetris Leadership Center case study, 477–484, 494–502 depth of recursion, 1272 deque (STL type), 1263–1265 front() member function, 1264 pop_front() member function, 1264 push_back() member function, 1264 dequeue operation, 1245–1246 dereferencing, of pointers, 530 derived class, 942 descending order, sorting in, 484 designing programs, 18–22 desk-checking, 21 destructors, 799–801, 956 base and derived classes, in, 954–955 virtual, 981–997 direct access file, 277 direct recursion, 1282 disk drive, 6 division by zero, 171, 1023–1024 dollarFormat function case study, 611–613 dot operator (.), 626, 648, 764
1349
1350
Index double data type, 56 double literals, 58
double precision, 56 doubly linked list, 1201 do-while loops, 252–256, 272 with menus, 254–257 as posttest loop, 252 drivers, 372–374 dummy parameter, 881 dynamic binding, 983 dynamic memory allocation, 540–544 bad_alloc exception, 1041 objects, 770–773, 791, 802 for structures, 650 dynamic queues, 1244, 1256–1263 dynamic stacks, 1214, 1231–1241
E
efficiency binary search, 477 linear search, 473–474 elements (array) accessing, 389–390 described, 388 processing, 408–416 removing, from vectors, 451–452 emplace() member function map class, 1094 multimap class, 1112 set class, 1119 vector class, 1086–1088 emplace_back() member function, vector class, 1086–1088 empty() member function array class, 1069 string class, 605 vector, 453–454, 455 encapsulation, 752 #endif directive, 778–779 endl, 33 end() member function array class, 1068, 1071 map class, 1197–1198 string class, 605 end of file, detecting, 289–291 end-of-file marker, 678 enqueue operation, 1244–1247 enum, 653–663 anonymous, 656 with arrays, 656–658 assigning, to int variables, 654 assigning integers to enum variables, 654 comparing enumerators, 654–655 declaration and definition, 662 defining, 662 math operators with, 656 outputting values with, 658–660 and scope, 661–662
specifying values, 660–661 strongly-typed, 662–663 enumerated data types, 653–663, see also enum enumerators, 654–655, 661–662 eof() member function, file stream, 686 equal-to operator (==), 154–155, 165–166 equal_range() member function, multiset class, 1123 erase() member function map class, 1095 multimap class, 1115 string class, 605 erase() member function map class, 1095 multimap class, 1115 errors logical, 21 off-by-one, 402–404 recovering from, 1034–1035 syntax, 12 error testing, files, 685–688 escape sequences, 34–36 \\, 35 \, 35 \a, 35 \b, 35 \n, 35 \r, 35 \t, 35 newline, 35 exception handler, 1024 exceptions, 1023–1041 bad_alloc, 1041–1042 catch block, 1024 dynamic memory allocation, 541 exceptions handler, 1024 extracting data from, 1036–1039 handling, 1024–1027 memory allocation error, 1041 multiple, handling, 1030–1035 new operator, 540 not catching, 1027 object-oriented handling, 1027–1030 recovering from errors, 1034–1035 rethrowing, 1040 throwing, 1024 throw key word, 1024 throw point, 1024 try block, 1024 try/catch construct, 1056–1059 unwinding the stack, 1071 executable file, 12 execute, 5 exhaustive algorithms, 1298–1303 exit() function, 369–371 exponents, 97–99 expressions, 87–139 algebraic, 96–99 arithmetic, 93–102
Index case study, 135–139 characters and string objects, 122–128 cin object, 87–92 conditional, 205–208 C-style and prestandard C++ forms, 109–110 formatting output, 112–122 and hand tracing programs, 133–135 initialization, 258, 262 mathematical, 93–102, 241 and mathematical library functions, 128–133 multiple and combined assignment, 108–112 overflow and underflow, 104–105 relational, 241–242 type casting, 105–108 type conversion, 102–103
F
factorial algorithm, 1277–1279 fail() member function, file stream, 292, 685, 686 false values, 154, 156–157, 164–165 fetch, 5 fetch/decode/execute cycle, 5 Fibonacci numbers, 1284–1285 field width, 113, 115 FIFO (first-in first out), 1243 file access flags, 676 ios::app, 676 ios::ate, 676 ios::badbit, 686 ios::binary, 676 ios::eofbit, 686 ios::failbit, 686 ios::goodbit, 686 ios::hardfail, 686 ios::in, 676 ios::out, 676 ios::trunc, 676 file access methods, 277 file buffer, 279 filename extensions, 277 filenames and file stream objects, 277–278 user-specified, 292–293 file open errors, 291–292 file operations, 675–748 append mode, 676 binary files, 698–703 described, 676 end-of-file marker, 678 fstream data type, 676, 677, 715 member functions for reading and writing, 688–695 opening files for input and output, 705–719 opening files with definition statements, 680–681 opening multiple files, 696–698 open modes of ifstream and ofstream, 679–680 random-access files, 707–715 reading a character, 688 reading a line, 690 records with structures, 703–707
rewinding, 714–715 writing a character, 694–695 files closing of, 279 for data storage, 275–293 detecting end of, 289–291 file open errors, 291–292 input/output program, 278 opening, and creating file objects, 278–279 processing, with loops, 288–289 reading from, 284, 286–287 read position, 285–286 types of, 276–277 user-specified filenames, 292–293 writing to, 280 file stream objects, 277 closing, 279 creating, 278–279 member functions, 688–695 passing to functions, 683–685 fill constructor vector class, 1076 fill(value) member function, array class, 1069 filters, 696 final, 995–996 find() member function map class, 1098 multimap class, 1113–1114 set class, 1119–1120 string class, 607–608 finding classes, 826–834 first-in first-out (FIFO), 1243 fixed manipulator, 118–119, 681 flags, 187–188 integer, 187 flash memory, 6 float data type, 56 floating-point data types, 56–59 comparing, 163–164 and integer variables, 58–59 floating-point literals, 57–58 floating point numbers, 45 float literals, 58 floppy disk drive, 6 flowcharts, 20 for loops, 257–267, 272 counter variable, 261 initialization expression, 258, 262 omitting expressions of, 262–266 as pretest loop, 261 range-based, 404–408 test expression, 258 update expression, 258, 262, 263–264 user-controlled, 262–263 while and do-while vs., 260–261 for_each() function, 1137–1138 formal argument, 321 formal parameters, 321
1351
1352
Index formatting output, 112–122, 681–683 fixed manipulator, 118–119 left manipulators, 120–121 right manipulators, 120–121 setprecision manipulator, 115–117 showpoint manipulator, 119–120 FORTRAN, 11 forward declaration, 859 forward_list class, 1206 friend class, 861 friend functions, 857–861 friend key word, 857 front() member function array class, 1069 deque, 1263–1264 fstream header file, 278 fstream objects, 676 function arguments file stream objects as, 683–685 structures as, 639–641 function call operator, 1153 function call statements, 312 function declarations, 319 function header, 311 function object anonymous, constructing, 1156 definition, 1153 function parameters pointers as, 530–538 reference variables as, 358–364 function pointer, 1137 function prototypes, 319–320 functions, 28 bool value, returning, 342–344 calling, 312–319 default arguments, 355–358, 796 defining, 310–311 exit(), 369–371 friend, 857–859 generic, 1043 inline, 783–785 local and global variables, 344–352 main, 28–29, 312, 478 member, 752 menu-driven programs, 328–332 modular programming, 309–310 overloading, 365–369 overriding, 992 passing data by value, 326–327 pointers, returning, 544–546 prototypes, 319–320 pure virtual, 997–1001 recursive, 1271–1275 redefining base class, 970–974 reference variables as parameters, 358–364 return statement, 332–333 sending data into, 321–325 static local variables, 352–355
static member, 854–856 string handling, 593–598 structures, returning, 642–644 stubs and drivers, 372–374 value-returning, 334–342 virtual, 983–984, 997–1001 void, 311 function signature, 366 function templates, 1043–1049 with multiple types, 1047–1048 overloading with, 1048–1049 using operators in, 1047
G
games, 275 GCD (greatest common divisor), 1283–1294 General Crates, Inc. case study, 135–139 generalization, inheritance and, 941–942 generic data types, 1043 generic functions, 1043 getline() member function, 123 cin, 575, 590–591 file streams, 690–693 get() member function, 124–126 file streams, 693–694 getter functions, 762 global constants, 348–350 global variables, 346–348 good() member function, file stream, 686 greatest common divisor (GCD), 1282–1284
H
handler, exception, 1056 hand tracing programs, 133–135 Hanoi, Towers of, 1291–1294 hardware, 3–7 CPU, 3–5 input devices, 6–7 main memory, 5–6 output devices, 7 secondary storage, 6 “has a” relationship, 900 header function, 311 loop, 243, 258 header file, 28 cmath, 98, 128 cstdlib, 370, 587 cstring, 576 fstream, 278 iomanip, 114, 117 iostream, 28, 37–38 STL, 1066 string, 54, 599
Index hexadecimal literals, 49 hiding data, 752, 763 hierarchies, class, 975–980 hierarchy chart, 20 high-level languages, 10 Hoare, C.A.R., 1294 Home Software Company case study, 611–613
I
identifiers, 43–44 capitalization, 44 legal, 44 if/else if statements, 180–182 nested decision structures vs., 184–185 trailing else, 183 if/else statements, 170–172 #ifndef directive, 778–779 if statement conditionally executed code, 160, 166–168 expanding, 166–169 floating-point comparisons, 163–164 nested, 173–176 programming style, 163 semicolon in, 162 ifstream objects, 278, 679 close() member function, 279 open() member function, 279 >> with, 284 ignore() member function, cin, 127, 591 image editors, 275 implementation file, class, 778 #include directive, 28, 37–39, 757, 778, 782 in-place initialization, 790 include file directory, 781 includes() function, 1141 include guard, 778–779 increment operator (++), 237–242 in mathematical expressions, 241 postfix and prefix modes, 239–241 in relational expressions, 241–242 indirection operator (*), 517 indirect recursion, 1282 infinite loops, 246 inheritance, 941–949 base class, 942 class hierarchies, 975–980 and class templates, 1054–1058 constructor, 967–968 constructors and destructors, 956–961 derived class, 942–943 “is a” relationship, 942–949 multiple, 1004–1011 redefining functions, 970–974 initialization, 62, 63 array, 394–397, 434–435, 635 for loops, 258, 262
pointers, 527–528 structure, 630–632 structure array, 635 inline expansion, 785 inline member functions, 783–785 inorder traversal, binary trees, 1316 input, 17–18 array contents, 390–394 with cin, 87–91 reading, into string objects, 600 input devices, 6–7 input file, 275, 278 input–output stream library, 37 input validation and decision making, 199–200 and while loops, 249–251 insert() member function map class, 1094 multimap class, 1112 set class, 1119 string class, 611–612 vector class, 1081–1083 instances of class, 755 of classes, 763–773 of structures, 626 variables, 849–850 instantiation, 763 int, 45, 46, 654 integer data types, 44–49 integer division, 65, 67, 103 integer flags, 187 integer literals, 48 integer variables, 58–59 integrated development environments (IDE), 13 iomanip header file, 114, 117 ios::app access flag, 676 ios::ate access flag, 676 ios::badbit status flag, 688 ios::binary access flag, 676, 699 ios::eofbit status flag, 688 ios::failbit status flag, 688 ios::goodbit status flag, 688 ios::hardfail status flag, 688 ios::in access flag, 676 ios::out access flag, 676 iostream header file, 28, 37–38 ios::trunc access flag, 676 isalnum() library function, 566 isalpha() library function, 566 “is a” relationship, 942–949, 981 is_permutation() function, 1136–1137 isdigit() library function, 566 islower() library function, 566 isprint() library function, 566 ispunct() library function, 566 isspace() library function, 566 isupper() library function, 566 iteration, 244
1353
1354
Index iterators, 1069–1075 association with containers, 1070 auto to define, 1073 categories of, 1070 definition, 1070–1071 and map class, 1097–1099 mutable, 1074–1075 reverse, 1074–1075 and set class, 1096–1097 usage in vector class, 1081–1082
J
Java, 11 JavaScript, 11
K
keyboard buffer, 91 key–value pairs, 1090 key words, 14
L
lambda expression, 1153, 1157–1158 language elements, 14 last-in-first-out (LIFO), 1213 left manipulator, 120–121 legacy code, 574 legal identifiers, 44 length, of C-strings, 576–577 length() member function, string class, 605, 611–612 library functions, 97 atof, 587 atoi, 587 atol, 587 for C-strings, 585–586 isalnum, 566 isalpha, 566 isdigit, 566 islower, 566 isprint, 566 ispunct, 566 isspace, 566 isupper, 566 strcat, 577–578, 585 strcmp, 582–584 strcpy, 578–579, 586 strlen, 576–577, 585 strncat, 579 strncpy, 579 strstr, 580–582, 586 tolower, 569 toupper, 569 lifetime, of variables, 346 LIFO (last-in, first-out), 1213 linear search algorithm for, 471–473 efficiency, 473–474 lines, 16 LinkedList class template, 1196 linked lists
appending a node, 1172–1177 arrays and vectors vs., 1169–1206 circularly, 1201 circularly linked, 1201 class as node type, 1196–1201 composition of, 1170 counting nodes, 1286–1287 declarations, 1170–1171 deleting a node, 1184–1185 described, 1169 destroying, 1189 displaying nodes in reverse, 1287–1289 doubly linked, 1201 inserting a node, 1179–1183 list head, 1170 NULL address, 1170–1171 operations, 1171–1189 recursion with, 1285–1289 self-referential data structure, 1171 singly linked, 1201 template for, 1190–1201 traversing, 1178–1179 variations of, 1201–1202 linker, 12 list class, 1202–1206 definition statements, 1202–1203 member functions, 1203–1205 list head, linked list, 1170 literals, 41–42 character, 50, 52–54 double, 58 float, 58 floating-point, 57–58 hexadecimal, 49 integer, 48–49 long integer, 48–49 octal, 49 string, 42, 52–54, 573–574 local scope, 219 local variables, 344–346 initializing, with parameter values, 346 lifetime of, 346 with same name as global, 351–352 static, 352–355 logical errors, 21 logical operators, 188–195 && (AND), 188–190 ! (NOT), 193–194, 584 || (OR), 191–193 associativity, 194–195 and numeric ranges, 195 precedence, 194–195 short-circuit evaluation, 189, 191 long data types, 45, 46 long double data types, 45, 46 long double precision, 56 long integer literals, 49 long long integer literal, 49 loop header, 243, 258 loops, 237–298
Index breaking and continuing, 294–298 conditional, 257 control variable, 245 count-controlled, 257, 265–266 counters, 251–252 described, 242 do-while, 252–256, 272 and files, 275–294 for, 257–267, 272, 404–408 and increment/decrement operators, 237–242 infinite, 246 input validation with, 249–251 nested, 272–274 posttest, 252–254 pretest, 245, 261 processing files with, 288–289 programming style, 247–248 range-based for loop, 404–408 running total, 267–269 selecting, 271–272 sentinels, 270–271 user-controlled, 254, 262–263 while, 242–248, 271 lowercase conversion, character, 569–571 low-level languages, 10 lvalues, 918–920 references, 920
M
machine language, 9 main function, 28–29, 480 main memory, 5–6 manipulators fixed, 118–119 left, 120–121 right, 120–121 setprecision, 115–117 showpoint, 119–120 stream, 33, 121 mantissa, 56 map class, 1090 add new elements to, 1093–1094 at() member function, 1095 definition statements, 1091 emplace() member function, 1094 erase() member function, 1095 initializing, 1092 insert() member function, 1094 iterators and, 1096–1099 keys in, 1106–1108 member functions, 1090–1092 range-based for loop, 1096 storing own classes objects as values in, 1102–1106 storing vectors as values in, 1099–1101 mathematical expressions, 93–102, 241 algebraic, to programming statements, 96–97 associativity, 95–96 exponents, 97–99
grouping with parentheses, 96 operator precedence, 94–95 mathematical library functions, 128–133 random numbers, 130–133 mathematical operators, with enum, 656 max_size() member function, array class, 1069 max_size() member function, vector class, 1088 member access specification defined, 954 inherited, 954 member functions, 752, 979 array class, 1069 binding, 982 dynamic binding, 983 getLength, 776 getObjectCount, 852 getTaxRate, 795 list class, 1203–1206 map class, 1090–1092 multimap class, 1109–1110 other overloaded, 807 overriding, 807 private, 807–809, 813 public, 813–814 redefining, 970–974, 992 set class, 1118 setLength, 776, 777 static, 854–856 static binding, 983 static stack class, 1215–1216 vector class, 1076–1079 virtual, 981–983 withdraw, 815 member initialization list, 790 usage with aggregate classes, 902 members, of structures, 623, 626–629, 651–652 member variable static stack class, 1215 memberwise assignment, 862–863 memory main, 5–6 random-access, 5 memory address, 6, 410 memory allocation, dynamic, see dynamic memory allocation memory leak, 541 avoiding, 550–553 memory requirements of arrays, 388–389 menu-driven programs, 196, 328–332 menus, 196–199, 213–217 message, 23 methods, 751 microprocessors, 4 modular program, 328 modular programming, 309–310 move semantics, 921–926 implementation in class, 926
1355
1356
Index multi-line comments, 73–74 multimap class, 1109 adding elements to, 1112 count() member function, 1112–1113 emplace() member function, 1112 erase() member function, 1115–1116 find() member function, 1113–1114 insert() member function, 1112 member functions, 1108–1109 multiple assignment, 108 multiple inheritance, 1004–1011 multiset class, 1123 mutable iterators, 1074–1075 mutators, 762
N
named constants, 74–76 names of functions, 311 of variables, 44, 220–221, 351–352 nameSlice functions, 594 namespaces, 28 National Commerce Bank, case study, 440–442 negation operator (2), 65, 95, 96 nested if statements, 173–180 nested loops, 272–274 break statement in, 295 nested structures, 635–638 newline escape sequence, 35 new operator, 540–542 nodes, 1169 appending, 1172–1177 of binary trees, 1309, 1314–1316, 1320–1329 class as node type, 1196–1201 counting, 1286–1287 deleting, 1184–1185, 1320–1329 displaying, in reverse, 1287–1289 inserting, 1179–1183, 1314–1316 of linked lists, 1169, 1172–1177, 1196–1201, 1286–1287 NOT (!) operator, 584 null character, 52, 572 null pointer, 516 nullptr, 516 null statement, 162 null terminator, 52, 572–573 numbers, 17 numbers, random, 130–133 numeric data checking ranges of, 195 integer data types for, 45 from text files, 286–287
O
object object object object
aggregation, 898–903 code, 12 conversion, 896–897 file, 12
object-oriented design aggregation, 898–903 class collaborations, 903–906 classes, finding, 826–834 CRC cards, 907–908 generalization and specialization, 941–942 inheritance, 941–949 problem domain, 827 responsibilities, identifying, 832–834 UML, 824–826, 902–903 object-oriented programming (OOP), 22, 23, 751–757 game simulation, 908–918 problem solving, 813–820 Unified Modeling Language, 824–826 object reusability, 754 objects, class vs., 751, 754–756 array of, 809–811 attributes, 752 data hiding, 752–753 dynamically allocated, 771–773, 791 encapsulation, 752 methods, 753 pointers, 770–773 state, 767 octal literals, 49 off-by-one error, 402–404 off position, 6 ofstream objects, 278, 679–680 close() member function, 279 open() member function, 279 and (object pointer), 771 −> (structure pointer), 648, 650–652 !, 188, 193–194, 584 !=, 154–156 % (modulus), 65, 95
Index %=, 109–111 &(address), 511–513 &&, 188–190, 399 * (indirection), 517 * (multiplication), 65, 95–96 * (pointer variable declaration), 651–652 *=, 109–111 . (dot operator), 626, 764 / (division), 65, 95 /=, 109–111 ?:, 206 || (OR), 188, 191–193 +, 65, 95, 604 ++, 237–241 +=, 109–111, 604 , 88, 604 [] operator, 442, 444–446, 604
associativity, 95–96, 194–195 binary, 64, 65 copy assignment, 873–875 overloading, 869–895 precedence of, 94–95, 194–195 relational, see relational operators scope resolution (::), 762 ternary, 64 unary, 64 OR with enum, 658–660 formatting, 681–683 || logical operator, 187–193 output, 18 output devices, 7 output file, 275, 278 overflow, 104–105 overhead, 1276 overloading functions, 365–369 constructors, 803–805 member functions, 799 templates, 1048 override, 995–997 overriding, 992
P
parallel arrays, 417–420 parameters array, 424 pointers as, 530–538 reference variables as, 358–364 parentheses, 96 partially filled arrays, 413–415 Pascal, 11
passing by value, 326–327 passing to functions with pointers, 596–598 percentage discounts, 68–71 permutations, algorithms for detection, 1135–1137 pointers, 511–558 address operator (&), 511–513 arithmetic with, 525–526 and arrays, 520–525 base class, 989–991 comparing, 528–530 constant, 537–538 constant, to constants, 538 to constants, 534–536 creating and using, 515–520 dynamic memory allocation, 540–545 as function parameters, 530–538 initializing, 527–528 to objects, 770–773 passing C-string arguments with, 596–598 returning, from a function, 544–546 smart, 550–553 structure pointer operator, 648, 651, 652 to structures, 647–650 structures containing, 707 United Cause case study, 554–559 pointer variables, see pointers polymorphism, 981–997 abstract base classes, 997–1001 base class pointers, 989–991 dynamic binding, 983 overriding, 992 pure virtual function, 997–1001 and references or pointers, 987–989 references/pointers, 987–989 static binding, 983 virtual destructors, 992–997 virtual functions, 997–1001 pop_back() member function vector, 455 pop_front() member function deque, 1263 pop operation (stacks), 1214 postfix mode, 239–241 postorder traversal, binary trees, 1316–1317 posttest loop, 252–254 pow() function, 97–99, 130 precedence, operator, 94–95, 194–195 predicate, 1157 prefix, template, 1043, 1047 prefix modes, 239–241 preorder traversal, binary trees, 1316 preprocessor, 11 preprocessor directive, 28, 30 prestandard C++ standard vs., 87–88 type cast expressions, 109–111 pretest loop, 245 priming read, 249
1357
1358
Index primitive data types, 622 priority_queue (adapter class), 1067 private member functions, 807–809 private members, class, 760–761, 776–777 problem domain, 827 procedural programming, 22–23, 751–755 processing, 19 processing array contents, 408–416 programmability, of computers, 1–2 programmer-defined data types, 442 programmer-defined identifiers, 14, 15 programmers, 2, 9 programming, 1–23 computer systems, 2–7 input, processing, and output, 17–18 procedural and object-oriented, 22–23 process of, 18–22 programability of computers, 1–2 program elements, 14–17 programs and progamming languages, 8–13 programming languages, 8–11, see also specific languages high-level, 10 low-level, 10 programming process, 18–22 programming style, 76–78 and if statements, 163 and nested decision structures, 176–177 and while loops, 247–248 programs defined, 1 described, 8–9 designing/creating, 18–22 elements, 14–17 primary activities of, 17–18 protected members, 950–955 prototypes, function, 319–320 pseudocode, 20–21, 66, 474 public member functions, 760–761 public members, class, 760–761 punctuation, 14, 15–16 pure virtual function, 997–1001 push_back() member function deque, 1263 vector, 448–449, 455 push operation (stacks), 1214 put() member function, file streams, 693–696 Python, 11
Q
queue (adapter class), 1067 queue (STL type), 1265–1266 queue container adapter, 1265–1266
queues, 1243–1266 applications of, 1244 array-based, 1231 crawling problem with array, 1246 dequeuing, 1244 described, 1243 dynamic, 1244, 1256–1259, 1256–1263
dynamic template, 1260–1263 empty, detecting, 1247 enqueuing, 1244–1247 first-in, first-out, 1243 full, detecting, 1247 linked list-based, 1256–1259 operations, 1244–1246 static, 1244, 1247–1251 static template, 1251–1255 STL queue and dequeue containers, 1265–1266 QuickSort algorithm, 1294–1298
R
RAM, 5 random-access files, 277, 707–715 random-access memory (RAM), 5 random file access, 707 random numbers, 130–133 range-based for loop, 404–408 map class, 1097 modifying array with, 406–408 set class, 1119–1120 versus regular for loop, 408 range constructor list class, 1203 map class, 1090 set class, 1117 vector class, 1077 range variable, 404 rbegin() member function, array class, 1069, 1074 reading data, from file, 284, 286–287 read() member function, file stream objects, 699–701 read position, 285–286 records, 703–707 recursion, 1271–1303 base case, 1276 binary search, 1289–1291 counting characters, 1279–1282 depth of, 1272 direct, 1282 exhaustive algorithms, 1298–1301 factorial algorithm, 1276–1279 Fibonacci numbers, 1284–1285 greatest common divisor (GCD), 1283–1284 indirect, 1282 infinite, 1271 iteration vs., 1303 linked list operations, 1285–1289 problem solving with, 1275–1282 QuickSort algorithm, 1294–1298 recursive functions, 1271–1275 recursively defined problems, 1284–1285 Towers of Hanoi, 1291–1294 recursive case, 1275 redefining base class functions, 970–974, 981 reference variables as parameters, 358–365 pointers vs., 530–531
Index reinterpret_cast, 701, 703 relational expressions, 154, 241–242 relational operators, 153–157 and characters, 201–202 and pointers, 528 and string class, 202–204 truth, 154–156 value of relationship, 154–156 relationships “has a,” 900 “is a,” 942–949, 981 whole-part, 900 rend() member function, array class, 1069, 1074 replace() member function, string class, 612 reserve() member function, vector class, 1088 reserved words, 15 resize() member function string class, 607 vector, 456 responsibilities, identifying, 832–834 rethrowing an exception, 1040 returning bool value from functions, 342–344 pointers from functions, 544–549 structures from functions, 642–644 values from functions, 334–339 return statement, 332–333 reusability, object, 754 reverse iterator, 1074–1075 rewinding a file, 714–715 right manipulators, 120–121 Ruby, 11 running, of programs, 5 running total (for loops), 267–269 run-time library, 12 rvalues, 62, 918–920 references, 920–921
S
scope, 64 scope resolution operator (::), 762, 856 search algorithm binary search, 474–477, 1289–1291 Demetris Leadership Center case study, 477–484 linear search, 471–474 for STL vector, 53–505 search trees, binary, 1311 secondary storage, 6 seekg() member function, file stream objects, 707–712 seekp() member function, file stream objects, 707–712 selection sort algorithm, 490–494 self-referential data structure, 1171 semicolons, 162 sentinels, 270–271 sequence containers, 1066 sequence structure, 158
sequential file access, 277, 707 seekg() member function, 714–715 sequential search, 471 set class, 1117 count() member function, 1120 definition statements, 1117 emplace() member function, 1119 find() member function, 1120–1121 insert() member function, 1118–1119 iterators and, 1120 member functions, 1203–1206 range-based for loop, 1119 store objects of class in, 1121–1123 set_difference() function, 1140, 1145–1146 set_intersection() function, 1140, 1143–1144 set_symmetric_difference() function, 1141, 1146–1147 set_union() function, 1140, 1141–1143 setprecision manipulator, 115–117, 681 setter functions, 762 setw manipulator, 682–683 shared_ptr, 550 short, 45, 46 short-circuit evaluation, 189, 191 showpoint manipulator, 119–120 shrink_to_fit() member function, vector class, 1088 single-line comments, 72–73 single precision, 56 singly linked list, 1201 size declarators, of arrays, 388 size() member function array class, 1068 string class, 612 vector, 450–451 sizeof operator, 60 smart pointers, 551–553 software application, 7 system, 7 software developers, 1 software development tools, 7 software engineering, 22, 1049, 1303 sort algorithm (STL), 484 sort() function, 1131–1135 sorting, of strings, 584–586, 600–602 sorting algorithm bubble sort, 484–487 Demetris Leadership Center case study, 494–502 QuickSort, 1294–1298 selection sort, 490–494 for STL vector, 503–505 source code, 11 source files, 11 specialization, inheritance and, 941–942 specialized templates, 1058 specification file, class, 777 spreadsheets, 275, 675 stack (adapter class), 1041 stack (STL type), 1241–1243
1359
1360
Index stacks, 1213–1268 applications of, 1214 array-based, 1214 cafeteria plates, 1213–1214 described, 1213–1214 dynamic, 1214, 1231–1232 implementing, 1221–1223 isEmpty() function, 1234 isEmpty operation, 1215 isFull operation, 1215 LIFO, 1213 linked list-based, 1231–1235 for math, 1221–1223 operations, 1214–1215, 1221–1223 pop, 1214–1215 push, 1214 static, 1214–1215, 1224–1230 STL stack container, 1241–1243 unwinding, 1039 stale data, 770 Standard Template Library (STL), 442, 1065 algorithms to perform set operations, 1140–1149 array class, 1067–1069 associative containers, 1066 forward_list class, 1206 functional classes in, 1159–1165 header files, 1067 includes() function, 1141 iterators (see iterators) list class, 1202–1206 queue, 1265–1266 sequence containers, 1066 set_difference() function, 1140, 1145–1146 set_intersection() function, 1140, 1143–1144 set_symmetric_difference() function, 1141, 1146–1147 set_union() function, 1140, 1141–1142 stack, 1241–1243 storing objects, 1241–1243 vector, 442–456, 503–506 state, object, 767 statements, 16 static binding, 983 static key word, 850 static local variables, 352–355 static member functions, 854–856 static member variables, 850–854 static queues, 1244, 1247–1251 template, 1251–1255 static stacks, 1214–1221, 1224–1230 STL, see Standard Template Library storage, secondary, 6 strcat() library function, 577–578, 585 strcmp() library function, 582–584 strcpy() library function, 578, 586 stream extraction operator, 88 stream insertion operator, 32, 280, 604 stream manipulator, 33, 121 stream object, 31
string class, 599–608, 757 append() member function, 607 assign() member function, 607 begin() member function, 607 capacity() member function, 607 clear() member function, 607 compare() member function, 607
comparing and sorting, 600–602 constructors, 803 copy() member function, 607 defining string objects, 599–600, 603–604 described, 54–55 empty() member function, 607 end() member function, 607 erase() member function, 607 find() member function, 607 Home Software Company case study, 611–613 input, reading into a string object, 600 insert() member function, 611 length() member function, 605, 608 at() member function, 607 member functions, 605–608 operators, 604 and relational operators, 202–204 replace() member function, 608 resize() member function, 608 size() member function, 608 substr() member function, 608 swap() member function, 608 using, 54–55 string constant, 29 string header file, 54, 599 string literals, 29, 42, 52–54, 573–574 string objects and characters, 122–128 comparing, 202–204 defining, 599–600, 603–604 functions for handling, 593–598 member functions and operators, 128 numeric conversion functions, 587–593 reading input into, 600 sorting, 584–587 string tokenizing, 608–610 strlen() library function, 576–577, 585 strncat() library function, 586 strncpy() library function, 586 strongly typed enum, 662–664 strstr() library function, 580–582, 585 struct, 623, see also structures structure pointer operator (−>), 648–650 structures, 621–664 and abstract data types, 621–623 accessing structure members, 626–629 arrays of, 633–635 combining data into, 623–626 containing pointers, 707 and enumerated data types, 653–664 as function arguments, 639–642 initializing, 630–632
Index nested, 635–638 pointers as members of, 651–652 pointers to, 647–650 records, creating with, 703–707 returning, from a function, 642–644 self-referential, 1171 structure variables, 625–626, 629 stubs, 372–374 subscript, of array element, 389 substr() member function, string class, 608 swap() member function, 455 array class, 1069 string class, 612 switch statement, 208–218 break, 210, 211 case, 209–210 default, 209–210 fallthrough capability, 211–213 with menus, 213–215 syntax, 14 syntax errors, 12 system software operating system, 7 software development tools, 7 utility program, 7
T
tags, of structures, 624, 626 tellg() member function, file stream objects, 712–714 tellp() member function, file stream objects, 712–714 template function, 1043 template prefix, 1043, 1050 templates binary trees, 1329–1336 class, 1050–1059 defining, 1048, 1049 dynamic queue, 1260–1263 dynamic stack, 1236–1241 function, 1043–1049 linked list, 1190–1201 prefixes, 1043 specialized, 1058 static queue, 1247–1255 static stack, 1224–1230 type parameter, 1043 ternary operators, 65, 205 text editor, 11 text files described, 276 numeric data from, 286–287 this pointer, 869, 871–872 throwing an exception, 541, 1024 throw key word, 1024, 1039 throw point, 1024 tolower() library function, 569 top-down design, 20 to_string() function, 589 toupper() library function, 569
Towers of Hanoi, 1291–1294 trailing else, 183 traversing binary tree, 1316–1319 linked list, 1178–1179 true values, 154, 156–157, 164–165 truth, 156–158, 164–165 try block, 1024 try/catch construct, 1024–1026 try key word, 1024 two-dimensional arrays, 431–438 initializing, 434–435 passing, to functions, 435–436 summing columns, 438 summing elements of, 437 summing rows, 437–438 type cast expression, 105 type casting, 105–108 type coercion, 102 type conversion, 102–103 type parameters, 1043–1045, 1047
U
UML, see Unified Modeling Language unary operator, 64 unary predicate, 1157 underflow, 104–105 Unified Modeling Language (UML), 824–826, 902–903 access specification, showing, 825 aggregation, showing, 902–903 class diagram, 824–826 constructors, showing, 826 destructors, showing, 826 parameter notation, 825–826 unique_ptr, 550–553 United Cause, case study, 553–558 unordered_multimap class, 1116 unordered_multiset class, 1123 unordered_set class, 1123 unsigned int, 45, 46 unsigned long, 45, 46 unsigned short, 45, 46 unwinding the stack, 1041 update expression (for loop), 258, 262, 263–264 multiple statements in, 263–264 uppercase conversion, character, 569–571 USB drives, 7 user-controlled loops, 254, 262–263 user-specified filenames, 292–293 utility programs, 7
V
value, passing by, 658 value-returning functions, 334–342 calling, 336–339 defining, 334–335 variable declaration, 17 variable definitions, 17, 39
1361
1362
Index variables, 16–17 compared to linked list, 1169 control, 245 defining, 443–444 flag, 187–188 global, 346–348 initialization list, with C++ 11, 444 instance, 849–856 integer, 45, 187–188 local, 344–346, 351–355 loop control, 245 names, 44 overflow and underflow, 104–105 storing and retrieving values in, 444–446 swap() member function, 455 with same name, 220–221, 351–352 static member, 850–856 structure, 625–626, 629 vector, 1076 basic operations, 1079–1080 capacity() member function, 1088 defining, 1079–1080 definition statements, 1076–1077 emplace() member function, 1086–1088 emplace_back() member function, 1086–1088 insert() member function, 1081–1083 iterators usage, 1081 max_size() member function, 1088 member functions, 1077–1079 reserve() member function, 1088
shrink_to_fit() member function, 1088 storing values in, 1084–1085 virtual destructors, 981–997 virtual functions and polymorphism, 987–989 pure, 997–1001 virtual key word, 983 virtual member functions, 981–997 Visual Basic, 11 void function, 311 volatile memory, RAM as, 5
W
weak_ptr, 550 Web browsers, 275 while loops, 242–248, 271 input validation with, 249–251 logic of, 243–245 as pretest loop, 245 programming style, 247–248 whitespace characters, 122 whole-part relationship, 900 word processors, 275, 675 write() member function, file stream objects, 699
Z
zero(es) division by, 171, 1023–1024 trailing, 119, 120
Credits Cover Image © Anna Kucherova/Shutterstock Figure 1-2a pg. 3 © Iko/Shutterstock Figure 1-2b pg. 3 © Nikita Rogul/Shutterstock Figure 1-2c pg. 3 © Feng Yu/Shutterstock Figure 1-2d pg. 3 © Chiyacat/Shutterstock Figure 1-2e pg. 3 © Elkostas/Shutterstock Figure 1-2f pg. 3 © Tkemot/Shutterstock Figure 1-2g pg. 3 © Kastianz/Shutterstock Figure 1-2h pg. 3 © StockPhotosArt/Shutterstock Figure 1-2i pg. 3 © Jocic/Shutterstock Figure 1-2j pg. 3 © Art gallery/Shutterstock Figure 1-2k pg. 3 © Peter Guess/Shutterstock Figure 1-2l pg. 3 © Aquila/Shutterstock Figure 1-2m pg. 3 © Andre Nitsievsky/Shutterstock Figure 1-3 pg. 4 © U.S. Army Center of Military History Figure 1-4 pg. 4 © Creativa/Shutterstock Chapter 1 Microsoft screenshots - SEE MICROSOFT AGREEMENT FOR FULL CREDIT LINE. Chapter 2 Microsoft screenshots - SEE MICROSOFT AGREEMENT FOR FULL CREDIT LINE. Chapter 5 Microsoft screenshots - SEE MICROSOFT AGREEMENT FOR FULL CREDIT LINE. Chapter 17 Microsoft screenshots - SEE MICROSOFT AGREEMENT FOR FULL CREDIT LINE. 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. 1363
This page intentionally left blank