get with the programming Through the power of practice and immediate personalized feedback, MyProgrammingLab improves your performance.
Learn more at www.myprogramminglab.com
STARTING OUT WITH
C++ From Control Structures through Objects SEVENTH EDITION
Tony Gaddis Haywood Community College
Addison-Wesley Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Editorial Director: Marcia Horton Editor-in-Chief: Michael Hirsch Editorial Assistant: Stephanie Sellinger Vice President, Marketing: Patrice Jones Marketing Manager: Yezan Alayan Marketing Coordinator: Kathryn Ferranti Vice President, Production: Vince O Brien Managing Editor: Jeff Holcomb Senior Production Project Manager: Marilyn Lloyd Senior Operations Supervisor: Alan Fischer
Manufacturing Buyer: Lisa McDowell Art Director: Linda Knowles Cover Designer: Joyce Cosentino Wells Cover Image: © Fotosearch/Rubberball Photos Media Editor: Daniel Sandin Media Project Manager: Wanda Rockwell Full-Service Vendor: Aptara®, Inc. Project Management: Dennis Free/Aptara®, Inc. Printer/Binder: Edwards Brothers Cover Printer: Lehigh-Phoenix Color
Copyright © 2012, 2009, 2007, 2005 Pearson Education, Inc., publishing as Addison-Wesley. 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 likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 501 Boylston Street, Suite 900, Boston, Massachusetts 02116. Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps. Library of Congress Cataloging-in-Publication Data Gaddis, Tony. Starting out with C++ : from control structures through objects / Tony 7th ed. Gaddis. p. cm. Includes bibliographical references and index. ISBN-13: 978-0-13-257625-3 (alk. paper) ISBN-10: 0-13-257625-2 (alk. paper) 1. C++ (Computer program language) I. Title. QA76.73.C153G33 2012 005.13'3 dc22 2011003252
10 9 8 7 6 5 4 3 2 1 EB
15 14 13 12 11
ISBN 13: 978-0-13-257625-3 ISBN 10: 0-13-257625-2
Contents at a Glance
CHAPTER 1 CHAPTER 2
Preface xiii Introduction to Computers and Programming 1 Introduction to C++ 27
CHAPTER 3 CHAPTER 4 CHAPTER 5 CHAPTER 6 CHAPTER 7 CHAPTER 8 CHAPTER 9 CHAPTER 10 CHAPTER 11 CHAPTER 12 CHAPTER 13 CHAPTER 14 CHAPTER 15 CHAPTER 16 CHAPTER 17 CHAPTER 18 CHAPTER 19 CHAPTER 20
Expressions and Interactivity 85 Making Decisions 149 Loops and Files 227 Functions 301 Arrays 377 Searching and Sorting Arrays 451 Pointers 491 Characters, C-Strings, and More About the String Class 541 Structured Data 593 Advanced File Operations 651 Introduction to Classes 705 More About Classes 799 Inheritance, Polymorphism, and Virtual Functions 869 Exceptions, Templates, and the Standard Template Library (STL) Linked Lists 1003 Stacks and Queues 1043 Recursion 1101 Binary Trees 1137
947
Appendix A: Getting Started with Alice 1167 Appendix B: The ASCII Character Set 1195 Appendix C: Operator Precedence and Associativity 1197 Quick References 1199 Index 1201 v
vi
Contents at a Glance
Online
The following appendices are available at www.pearsonhighered.com/gaddis. Appendix D: Introduction to Flowcharting Appendix E: Using UML in Class Design Appendix F: Namespaces Appendix G: Writing Managed C++ Code for the .NET Framework Appendix H: Passing Command Line Arguments Appendix I: Header File and Library Function Reference Appendix J: Binary Numbers and Bitwise Operations Appendix K: Multi-Source File Programs Appendix L: Stream Member Functions for Formatting Appendix M: Introduction to Microsoft Visual C++ 2010 Express Edition Appendix N: Answers to Checkpoints Appendix O: Solutions to Odd-Numbered Review Questions
Contents Preface xiii CHAPTER 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7
Introduction to Computers and Programming 1 Why Program? 1 Computer Systems: Hardware and Software 3 Programs and Programming Languages 8 What Is a Program Made of? 13 Input, Processing, and Output 17 The Programming Process 18 Procedural and Object-Oriented Programming 22
CHAPTER 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 2.13 2.14 2.15 2.16 2.17 2.18
Introduction to C++ 27 The Parts of a C++ Program 27 The cout Object 31 The #include Directive 36 Variables and Literals 37 Identifiers 41 Integer Data Types 42 The char Data Type 47 The C++ string Class 51 Floating-Point Data Types 53 The bool Data Type 56 Determining the Size of a Data Type 57 Variable Assignments and Initialization 58 Scope 59 Arithmetic Operators 60 Comments 68 Named Constants 70 Programming Style 72 If You Plan to Continue in Computer Science: Standard and Prestandard C++ 74
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
Expressions and Interactivity 85 The cin Object 85 Mathematical Expressions 91 When You Mix Apples and Oranges: Type Conversion Overflow and Underflow 102 Type Casting 103 Multiple Assignment and Combined Assignment 107 Formatting Output 111 Working with Characters and string Objects 120 More Mathematical Library Functions 127 Focus on Debugging: Hand Tracing a Program 130 Focus on Problem Solving: A Case Study 132
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
Making Decisions 149 Relational Operators 149 The if Statement 154 Expanding the if Statement 162 The if/else Statement 166 Nested if Statements 169 The if/else if Statement 176 Flags 181 Logical Operators 182 Checking Numeric Ranges with Logical Operators 189 Menus 190 Focus on Software Engineering: Validating User Input 193 Comparing Characters and Strings 195 The Conditional Operator 199 The switch Statement 202 More About Blocks and Scope 211
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
Loops and Files 227 The Increment and Decrement Operators 227 Introduction to Loops: The while Loop 232 Using the while Loop for Input Validation 239 Counters 241 The do-while Loop 242 The for Loop 247 Keeping a Running Total 257 Sentinels 260 Focus on Software Engineering: Deciding Which Loop to Use Nested Loops 262 Using Files for Data Storage 265 Optional Topics: Breaking and Continuing a Loop 285
CHAPTER 6 6.1 6.2 6.3 6.4
Functions 301 Focus on Software Engineering: Modular Programming Defining and Calling Functions 303 Function Prototypes 311 Sending Data into a Function 313
100
301
261
Contents
6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 6.15 6.16
Passing Data by Value 318 Focus on Software Engineering: Using Functions in a Menu-Driven Program The return Statement 324 Returning a Value from a Function 326 Returning a Boolean Value 334 Local and Global Variables 336 Static Local Variables 344 Default Arguments 347 Using Reference Variables as Parameters 350 Overloading Functions 356 The exit() Function 360 Stubs and Drivers 363
CHAPTER 7 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 7.11
Arrays 377 Arrays Hold Multiple Values 377 Accessing Array Elements 379 No Bounds Checking in C++ 386 Array Initialization 389 Processing Array Contents 394 Focus on Software Engineering: Using Parallel Arrays 402 Arrays as Function Arguments 405 Two-Dimensional Arrays 416 Arrays with Three or More Dimensions 423 Focus on Problem Solving and Program Design: A Case Study 424 If You Plan to Continue in Computer Science: Introduction to the STL vector 427
CHAPTER 8 8.1 8.2 8.3 8.4 8.5
Searching and Sorting Arrays 451 Focus on Software Engineering: Introduction to Search Algorithms 451 Focus on Problem Solving and Program Design: A Case Study 458 Focus on Software Engineering: Introduction to Sorting Algorithms 464 Focus on Problem Solving and Program Design: A Case Study 472 If You Plan to Continue in Computer Science: Sorting and Searching vectors 480
CHAPTER 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10
Pointers 491 Getting the Address of a Variable 491 Pointer Variables 493 The Relationship Between Arrays and Pointers 500 Pointer Arithmetic 504 Initializing Pointers 506 Comparing Pointers 507 Pointers as Function Parameters 509 Focus on Software Engineering: Dynamic Memory Allocation 518 Focus on Software Engineering: Returning Pointers from Functions 522 Focus on Problem Solving and Program Design: A Case Study 529
CHAPTER 10 10.1 10.2
Characters, C-Strings, and More About the string Class 541 Character Testing 541 Character Case Conversion 545
320
ix
x
Contents
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
C-Strings 548 Library Functions for Working with C-Strings 552 C-String/Numeric Conversion Functions 563 Focus on Software Engineering: Writing Your Own C-String-Handling Functions 568 More About the C++ string Class 574 Focus on Problem Solving and Program Design: A Case Study
Structured Data 593 Abstract Data Types 593 Focus on Software Engineering: Combining Data into Structures 595 Accessing Structure Members 598 Initializing a Structure 602 Arrays of Structures 605 Focus on Software Engineering: Nested Structures 608 Structures as Function Arguments 612 Returning a Structure from a Function 615 Pointers to Structures 618 Focus on Software Engineering: When to Use ., When to Use ->, and When to Use * 621 Unions 623 Enumerated Data Types 627
CHAPTER 12 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 12.10
Advanced File Operations 651 File Operations 651 File Output Formatting 658 Passing File Stream Objects to Functions 660 More Detailed Error Testing 662 Member Functions for Reading and Writing Files 665 Focus on Software Engineering: Working with Multiple Files Binary Files 674 Creating Records with Structures 679 Random-Access Files 683 Opening a File for Both Input and Output 691
CHAPTER 13 13.1 13.2 13.3 13.4 13.5
Introduction to Classes 705 Procedural and Object-Oriented Programming 705 Introduction to Classes 712 Defining an Instance of a Class 717 Why Have Private Members? 728 Focus on Software Engineering: Separating Class Specification from Implementation 729 Inline Member Functions 735 Constructors 738 Passing Arguments to Constructors 742 Destructors 750 Overloading Constructors 754 Private Member Functions 758 Arrays of Objects 759
13.6 13.7 13.8 13.9 13.10 13.11 13.12
584
672
Contents
13.13 13.14 13.15 13.16
Focus on Problem Solving and Program Design: An OOP Case Study 763 Focus on Object-Oriented Programming: Creating an Abstract Array Data Type 770 Focus on Object-Oriented Design: The Unified Modeling Language (UML) 774 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 777
CHAPTER 14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8
More About Classes 799 Instance and Static Members 799 Friends of Classes 807 Memberwise Assignment 812 Copy Constructors 813 Operator Overloading 819 Object Conversion 846 Aggregation 849 Focus on Object-Oriented Design: Class Collaborations
CHAPTER 15 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8
Inheritance, Polymorphism, and Virtual Functions 869 What Is Inheritance? 869 Protected Members and Class Access 878 Constructors and Destructors in Base and Derived Classes 884 Redefining Base Class Functions 896 Class Hierarchies 901 Polymorphism and Virtual Member Functions 907 Abstract Base Classes and Pure Virtual Functions 921 Multiple Inheritance 928
CHAPTER 16 16.1 16.2 16.3 16.4 16.5
Exceptions, Templates, and the Standard Template Library (STL) 947 Exceptions 947 Function Templates 966 Focus on Software Engineering: Where to Start When Defining Templates 972 Class Templates 973 Introduction to the Standard Template Library (STL) 983
CHAPTER 17 17.1 17.2 17.3 17.4 17.5
Linked Lists 1003 Introduction to the Linked List ADT 1003 Linked List Operations 1005 A Linked List Template 1022 Variations of the Linked List 1034 The STL list Container 1035
CHAPTER 18 18.1 18.2 18.3 18.4 18.5 18.6
Stacks and Queues 1043 Introduction to the Stack ADT 1043 Dynamic Stacks 1060 The STL stack Container 1071 Introduction to the Queue ADT 1073 Dynamic Queues 1085 The STL deque and queue Containers
1092
853
xi
xii
Contents
CHAPTER 19 19.1 19.2 19.3 19.4 19.5 19.6 19.7 19.8 19.9 19.10 CHAPTER 20 20.1 20.2 20.3
Recursion 1101 Introduction to Recursion 1101 Solving Problems with Recursion 1106 Focus on Problem Solving and Program Design: The Recursive gcd Function 1113 Focus on Problem Solving and Program Design: Solving Recursively Defined Problems 1114 Focus on Problem Solving and Program Design: Recursive Linked List Operations 1116 Focus on Problem Solving and Program Design: A Recursive Binary Search Function 1119 The Towers of Hanoi 1122 Focus on Problem Solving and Program Design: The QuickSort Algorithm Exhaustive Algorithms 1130 Focus on Software Engineering: Recursion vs. Iteration 1132
1125
Binary Trees 1137 Definition and Applications of Binary Trees 1137 Binary Search Tree Operations 1140 Template Considerations for Binary Search Trees 1157 Appendix A: Getting Started with Alice 1167 Appendix B: The ASCII Character Set 1195 Appendix C: Operator Precedence and Associativity 1197 Quick References 1199 Index 1201
Online
The following appendices are available at www.pearsonhighered.com/gaddis. Appendix D: Introduction to Flowcharting Appendix E: Using UML in Class Design Appendix F: Namespaces Appendix G: Writing Managed C++ Code for the .NET Framework Appendix H: Passing Command Line Arguments Appendix I: Header File and Library Function Reference Appendix J: Binary Numbers and Bitwise Operations Appendix K: Multi-Source File Programs Appendix L: Stream Member Functions for Formatting Appendix M: Introduction to Microsoft Visual C++ 2010 Express Edition Appendix N: Answers to Checkpoints Appendix O: Solutions to Odd-Numbered Review Questions
Preface Welcome to Starting Out with C++: From Control Structures through Objects, 7th 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 nd this text bene cial. 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.
Changes in the Seventh Edition This book s pedagogy, organization, and clear writing style remain the same as in the previous edition. Many improvements have been made, which are summarized here: This edition uses string objects, instead of char arrays, as the preferred way to store strings. This change has been made throughout the entire book. A thorough discussion of C-strings and the technique of storing them in char arrays is provided as a topic in Chapter 10. All of the introductory file I/O material has been consolidated and moved to Chapter 5. In previous editions, this material was gradually introduced in Chapters 3 through 5. Many reviewers requested that all the material be given in one place, after loops have been covered. Named constants are now introduced in Chapter 2, after variables. In Chapter 2 an additional In the Spotlight section demonstrating the modulus operator has been added. Chapter 4 has been reorganized so that all the fundamental decision structure topics appear early in the chapter. A discussion of passing arrays using const references has been added to Chapter 7.
xiii
xiv
Preface
An In the Spotlight section giving an additional example of inheritance has been added to Chapter 15. Template examples for stacks, queues, and binary search trees have been added to Chapters 18 and 20. The Serendipity Booksellers project has been moved to the book s online resource page at www.pearsonhighered.com/gaddis.
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 exibility 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 has already mastered 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. After Chapter 7 has been covered, you may proceed to Chapter 8, or jump to either Chapter 9 or Chapter 12. (If you jump to Chapter 12 at this point, you will need to postpone sections 12.7, 12.8, and 12.10 until Chapters 9 and 11 have been covered.) After Chapter 9 has been covered, either of Chapters 10 or 11 may be covered. After Chapter 11, you may cover Chapters 13 through 17 in sequence. Next you can proceed to either Chapter 18 or Chapter 19. Finally, Chapter 20 may be covered. This text s approach starts with a rm 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 eld 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, ow charts, and hierarchy charts are also presented.
Chapter 2: Introduction to C++ This chapter gets the student started in C++ by introducing data types, identi ers, variable declarations, constants, comments, program output, simple arithmetic operations, and Cstrings. Programming style conventions are introduced and good programming style is modeled here, as it is throughout the text. An optional section explains the difference between ANSI standard and pre-standard C++ programs.
Preface
Figure P-1 Chapter 1 Introduction
Chapters 2 7 Basic Language Elements
Chapter 8 Searching And Sorting Arrays
Chapter 12 Advanced File Operations*
Chapter 9 Pointers
*A few subtopics in Chapter 12 require Chapters 9 and 11.
Chapter 10 Characters, Strings, and the string Class
Chapter 11 Structures
Chapter 13 Introduction to Classes
Chapter 14 More About Classes
Chapter 15 Inheritance and Polymorphism
Chapter 16 Exceptions, Templates, and STL
Chapter 17 Linked Lists
Chapter 18 Stacks and Queues
Chapter 19 Recursion
Chapter 20 Binary Trees
xv
xvi
Preface
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 ow 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 le I/O is also introduced. The student learns to read and write text les, and use loops to process the data in a le.
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 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 In this chapter the student learns to create and work with single and multidimensional arrays. Many examples of array processing are provided including examples illustrating how to nd 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 le as an input source to populate an array. STL vectors are introduced and compared to arrays.
Chapter 8: Sorting and Searching 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.
Preface
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 les. The various modes for opening les are discussed, as well as the many methods for reading and writing le contents. Advanced output formatting is also covered.
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 speci cations, 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 nd the classes in a particular problem.
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 and Polymorphism 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.
xvii
xviii
Preface
Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) 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. Finally, the student is introduced to the containers, iterators, and algorithms offered by the Standard Template Library (STL).
Chapter 17: 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 18: Stacks and Queues In this chapter the student learns to create and use static and dynamic stacks and queues. The operations of stacks and queues are de ned, and templates for each ADT are demonstrated.
Chapter 19: 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 nding factorials, nding 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.
Chapter 20: 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.
Appendix A: Getting Started with Alice This appendix gives a quick introduction to Alice. Alice is free software that can be used to teach fundamental programming concepts using 3D graphics.
Appendix B: ASCII Character Set A list of the ASCII and Extended ASCII characters and their codes.
Appendix C: Operator Precedence and Associativity A chart showing the C++ operators and their precedence.
Preface
The following appendices are available online at www.pearsonhighered.com/gaddis.
Appendix D: Introduction to Flowcharting A brief introduction to owcharting. This tutorial discusses sequence, selection, case, repetition, and module structures.
Appendix E: Using UML in Class Design This appendix shows the student how to use the Uni ed Modeling Language to design classes. Notation for showing access speci cation, data types, parameters, return values, overloaded functions, composition, and inheritance are included.
Appendix F: Namespaces This appendix explains namespaces and their purpose. Examples showing how to de ne a namespace and access its members are given.
Appendix G: Writing Managed C++ Code for the .NET Framework This appendix introduces the student to the concepts surrounding managed C++ in Microsoft s .NET environment.
Appendix H: 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 I: Header File and Library Function Reference This appendix provides a reference for the C++ library functions and header les discussed in the book.
Appendix J: Binary Numbers and Bitwise Operations A guide to the C++ bitwise operators, as well as a tutorial on the internal storage of integers.
Appendix K: Multi-Source File Programs Provides a tutorial on creating programs that consist of multiple source les. Function header les, class speci cation les, and class implementation les are discussed.
Appendix L: Stream Member Functions for Formatting Covers stream member functions for formatting such as setf.
Appendix M: Introduction to Microsoft Visual C++ 2010 Express Edition A tutorial on how to start a project in Microsoft Visual C++ 2010 Express Edition, compile a program, save source les, and more.
xix
xx
Preface
Appendix N: 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 O: Solutions 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
A series of online videos, developed speci cally for this book, is available for viewing at www.pearsonhighered.com/gaddis. Icons appear throughout the text alerting the student to videos about speci c topics.
Checkpoints
Checkpoints are questions placed throughout each chapter as a self-test study aid. Answers for all Checkpoint questions can be downloaded from the book s Companion Website at www.pearsonhighered.com/gaddis. This allows students to check how well they have learned a new topic.
Notes
Notes appear at appropriate places throughout the text. They are short explanations of interesting or often misunderstood points relevant to the topic at hand.
Warnings
Warnings are notes that caution the student about certain C++ features, programming techniques, or practices that can lead to malfunctioning programs or lost data.
VideoNote
Preface
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.
Review Questions and Exercises
Each chapter presents a thorough and diverse set of review questions, such as ll-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 Website at www.pearsonhighered.com/gaddis.
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.
Software Development Project: Serendipity Booksellers
Available for download from the book s Companion Website at www.pearsonhighered.com/gaddis. This is an on-going project that instructors can optionally assign to teams of students. It systematically develops a real-world software package: a point-of-sale program for the ctitious Serendipity Booksellers organization. The Serendipity assignment for each chapter adds more functionality to the software, using constructs and techniques covered in that chapter. When complete, the program will act as a cash register, manage an inventory database, and produce a variety of reports.
C++ Quick Reference Guide
For easy access, a quick reference guide to the C++ language is printed on the last two pages of Appendix C in the book.
xxi
xxii
Preface
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 Website at www.pearsonhighered.com/gaddis: The source code for each example program in the book Access to the book s companion 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 The complete Serendipity Booksellers Project
Integrated Development Environment (IDE) Resource Kits Professors who adopt this text can order it for students with a kit containing ve popular C++ IDEs (Microsoft® Visual Studio 2010 Express Edition, Dev C++, NetBeans, Eclipse, and CodeLite) and access to a Web site containing written and video tutorials for getting started in each IDE. For ordering information, please contact your campus Pearson Education representative or visit www.pearsonhighered.com/cs.
Online Practice and Assessment with MyProgrammingLab MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages. A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice problems organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to gure out what went wrong and why. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review. MyProgrammingLab is offered to users of this book in partnership with Turing s Craft, the makers of the CodeLab interactive programming exercise system. For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com.
Instructor Resources The following supplements are available to quali ed instructors only: Answers to all Review Questions in the text Solutions for all Programming Challenges in the text PowerPoint presentation slides for every chapter
Preface
Computerized test bank Answers to all Student Lab Manual questions Solutions for all Student Lab Manual programs Visit the Pearson Instructor Resource Center (www.pearsonhighered.com/irc) or send an email to
[email protected] for information on how to access them.
Textbook Web site Student and instructor resources, including links to download Microsoft® Visual C++ 2010 Express and other popular IDEs, for all the books in the Gaddis Starting Out With series can be accessed at the following URL: http://www.pearsonhighered.com/gaddis
Get this book the way you want it! This book is part of Pearson Education s custom database for Computer Science textbooks. Use our online PubSelect system to select just the chapters you need from this, and other, Pearson Education CS textbooks. You can edit the sequence to exactly match your course organization and teaching approach. Visit www.pearsoncustom.com/cs for details.
Which Gaddis C++ book is right for you? The Starting Out with C++ Series includes three books, one of which is sure to t 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. FROM CONTROL STRUCTURES THROUGH OBJECTS BRIEF VERSION
EARLY OBJECTS
LATE INTRODUCTION OF OBJECTS Classes are introduced in Chapter 13 of the standard text and Chapter 11 of 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.
EARLIER INTRODUCTION OF OBJECTS 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 Linked lists, stacks and queues, and binary trees are introduced in the nal chapters of the standard text. 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.
INTRODUCTION OF DATA STRUCTURES AND RECURSION Linked lists, stacks and queues, and binary trees are introduced in the nal chapters of the text, after the chapter on recursion.
xxiii
xxiv
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
Royce Curtis Western Wisconsin Technical College
David Akins El Camino College
Joseph DeLibero Arizona State University
Steve Allan Utah State University
Jeanne Douglas University of Vermont
Vicki Allan Utah State University
Michael Dowell Augusta State U
Karen M. Arlien Bismark State College
William E. Duncan Louisiana State University
Mary Astone Troy University
Judy Etchison Southern Methodist University
Ijaz A. Awan Savannah State University
Dennis Fairclough Utah Valley State College
Robert Baird Salt Lake Community College
Mark Fienup University of Northern Iowa
Don Biggerstaff Fayetteville Technical Community College
Richard Flint North Central College
Michael Bolton Northeastern Oklahoma State University
Ann Ford Tyson Florida State University
Bill Brown Pikes Peak Community College
Jeanette Gibbons South Dakota State University
Charles Cadenhead Richland Community College
James Gifford University of Wisconsin, Stevens Point
Randall Campbell Morningside College
Leon Gleiberman Touro College
Wayne Caruolo Red Rocks Community College
Barbara Guillott Louisiana State University
Cathi Chambley-Miller Aiken Technical College
Ranette Halverson, Ph.D. Midwestern State University
C.C. Chao Jacksonville State University
Carol Hannahs University of Kentucky
Joseph Chao Bowling Green State University
Dennis Heckman Portland Community College
Preface
Ric Heishman George Mason University
James McGuffee Austin Community College
Michael Hennessy University of Oregon
Dean Mellas Cerritos College
Ilga Higbee Black Hawk College
Lisa Milkowski Milwaukee School of Engineering
Patricia Hines Brookdale Community College
Marguerite Nedreberg Youngstown State University
Mike Holland Northern Virginia Community College
Lynne O Hanlon Los Angeles Pierce College
Mary Hovik Lehigh Carbon Community College
Frank Paiano Southwestern Community College
Richard Hull Lenoir-Rhyne College
Theresa Park Texas State Technical College
Chris Kardaras North Central College
Mark Parker Shoreline Community College
Willard Keeling Blue Ridge Community College
Tino Posillico SUNY Farmingdale
A.J. Krygeris Houston Community College
Frederick Pratter Eastern Oregon University
Sheila Lancaster Gadsden State Community College
Susan L. Quick Penn State University
Ray Larson Inver Hills Community College
Alberto Ramon Diablo Valley College
Jennifer Li Ohlone College
Bazlur Rasheed Sault College of Applied Arts and Technology
Norman H. Liebling San Jacinto College
Farshad Ravanshad Bergen Community College
Zhu-qu Lu University of Maine, Presque Isle
Dolly Samson Weber State University
Heidar Malki University of Houston
Ruth Sapir SUNY Farmingdale
Debbie Mathews J. Sargeant Reynolds
Jason Schatz City College of San Francisco
Rick Matzen Northeastern State University
Dr. Sung Shin South Dakota State University
Robert McDonald East Stroudsburg University
Bari Siddique University of Texas at Brownsville
xxv
xxvi
Preface
William Slater Collin County Community College
David Topham Ohlone College
Shep Smithline University of Minnesota
Robert Tureman Paul D. Camp Community College
Caroline St. Claire North Central College
Arisa K. Ude Richland College
Kirk Stephens Southwestern Community College
Peter van der Goes Rose State College
Cherie Stevens South Florida Community College
Stewart Venit California State University, Los Angeles
Dale Suggs Campbell University
Judy Walters North Central College
Mark Swanson Red Wing Technical College
John H. Whipple Northampton Community College
Ann Sudell Thorn Del Mar College
Aurelia Williams Norfolk State University
Martha Tillman College of San Mateo
Vida Winans Illinois Institute of Technology
Ralph Tomlinson Iowa State University I would like to thank my family for their love and support in all of my many projects. I would also like to thank Christopher Rich for his assistance in this revision. I am extremely fortunate to have Michael Hirsch as my editor, and Stephanie Sellinger as editorial assistant. Michael s support and encouragement makes it a pleasure to write chapters and meet deadlines. I am also fortunate to have Yez Alayan as marketing manager, and Kathryn Ferranti as marketing coordinator. They do a great job getting my books out to the academic community. I had a great production team led by Jeff Holcomb, Managing Editor, and Marilyn Lloyd, Senior Production Project Manager. Thanks to you all!
Preface
About the Author Tony Gaddis is the principal author of the Starting Out with series of textbooks. He has nearly 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++, JavaTM, Microsoft® Visual Basic®, Microsoft® Visual C#, and Python, all published by Pearson Addison-Wesley.
xxvii
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? CO NCE PT: Computers can do many different jobs because they are programmable. Think about some of the different ways that people use computers. In school, students use computers for tasks such as writing papers, searching for articles, sending e-mail, and participating in online classes. At work, people use computers to analyze data, make presentations, conduct business transactions, communicate with customers and coworkers, control machines in manufacturing facilities, and do many other things. At home, people use computers for tasks such as paying bills, shopping online, social networking, and playing computer games. And don t forget that smart phones, iPods®, car navigation systems, and many other devices are computers as well. The uses of computers are almost limitless in our everyday lives. Computers can do such a wide variety of things because they can be programmed. This means that computers are not designed to do just one job, but 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. 1
2
Chapter 1 Introduction to Computers and Programming
Figure 1-1
A word processing program and a presentation program
Programs are commonly referred to as software. Software is essential to a computer because without software, a computer can do nothing. All of the software that we use to make our computers useful is created by individuals known as programmers or software developers. A programmer, or software developer, is a person with the training and skills necessary to design, create, and test computer programs. Computer programming is an exciting and rewarding career. Today, you will nd programmers working in business, medicine, government, law enforcement, agriculture, academics, entertainment, and almost every other eld. 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 Manuals and other forms of written documentation There is also a scienti c, or engineering, side to programming. Because programs rarely work right the rst 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 scienti c nature of programming make writing computer software like designing a car: Both cars and programs should be functional, ef cient, powerful, easy to use, and pleasing to look at.
1.2 Computer Systems: Hardware and Software
1.2
Computer Systems: Hardware and Software CON CE PT: All computer systems consist of similar hardware devices and software components. This section provides an overview of standard computer hardware and software organization.
Hardware Hardware refers to the physical components that a computer is made of. 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: 1. The central processing unit (CPU) 2. Main memory 3. Secondary storage devices 4. Input devices 5. Output devices The organization of a computer system is depicted in Figure 1-2. Figure 1-2
Central Processing Unit
Output Devices
Input Devices
Main Memory (RAM) Secondary Storage Devices
3
4
Chapter 1 Introduction to Computers and Programming
The CPU When a computer is performing the tasks that a program tells it to do, we say that the computer is running or executing the program. The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU is the most important component in a computer because without it, the computer could not run software. In the earliest computers, CPUs were huge devices that weighed tons. They were made of electrical and mechanical components such as vacuum tubes and switches. Today, CPUs are small chips, known as microprocessors, that can be held in the palm of your hand. In addition to being much smaller than the old electromechanical CPUs in early computers, today s microprocessors are also much more powerful. The CPU s job is to fetch instructions, follow the instructions, and produce some result. Internally, the central processing unit consists of two parts: the control unit and the arithmetic and logic unit (ALU). The control unit coordinates all of the computer s operations. It is responsible for determining where to get the next instruction and regulating the other major components of the computer with control signals. The arithmetic and logic unit, as its name suggests, is designed to perform mathematical operations. The organization of the CPU is shown in Figure 1-3. Figure 1-3 Central Processing Unit Arithmetic and Logic Unit Result (Output)
Instruction (Input) 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.
1.2 Computer Systems: Hardware and Software
Main Memory You can think of main memory as the computer s work area. This is where the computer stores a program while the program is running, as well as the data that the program is working with. For example, suppose you are using a word processing program to write an essay for one of your classes. While you do this, both the word processing program and the essay are stored in main memory. Main memory is commonly known as random-access memory or RAM. It is called this because the CPU is able to quickly access data stored at any random location in 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 anything meaningful, a computer must have lots of bytes. Most computers today have millions, or even billions, of bytes of memory. Each byte is divided into eight smaller storage locations known as bits. The term bit stands for binary digit. Computer scientists usually think of bits as tiny switches that can be either on or off. Bits aren t actual switches, however, at least not in the conventional sense. In most computer systems, bits are tiny electrical components that can hold either a positive or a negative charge. Computer scientists think of a positive charge as a switch in the on position and a negative charge as a switch in the off position. Each byte is assigned a unique number known as an address. The addresses are ordered from lowest to highest. A byte is identi ed by its address in much the same way a post of ce box is identi ed by an address. Figure 1-4 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-4 0
1
2
3
4
5
6
10
11
12
13
14
15
16
20
21
22
23
24
25
26
72
149
7
8
9
17
18
19
27
28
29
Secondary Storage Secondary storage is a type of memory that can hold data for long periods of time even when there is no power to the computer. Frequently used programs are stored in secondary memory and loaded into main memory as needed. Important information, such as word processing documents, payroll data, and inventory gures, is saved to secondary storage as well. The most common type of secondary storage device is the disk drive. A disk drive stores data by magnetically encoding it onto a circular disk. Most computers have a disk drive mounted inside their case. External disk drives, which connect to one of the computer s
5
6
Chapter 1 Introduction to Computers and Programming
communication ports, are also available. External disk drives can be used to create backup copies of important data or to move data to another computer. In addition to external disk drives, many types of devices have been created for copying data, and for moving it to other computers. For many years oppy disk drives were popular. A oppy disk drive records data onto a small oppy disk, which can be removed from the drive. The use of oppy disk drives has declined dramatically in recent years, in favor of superior devices such as USB drives. USB drives are small devices that plug into the computer s USB (universal serial bus) port, and appear to the system as a disk drive. USB drives, which use ash memory to store data, are inexpensive, reliable, and small enough to be carried in your pocket. Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are also popular for data storage. Data is not recorded magnetically on an optical disc, but is encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect the pits and thus read the encoded data. Optical discs hold large amounts of data, and because recordable CD and DVD drives are now commonplace, they are good mediums for creating backup copies of data.
Input Devices Input is any information the computer collects from the outside world. The device that collects the information and sends it to the computer is called an input device. Common input devices are the keyboard, mouse, scanner, digital camera, and 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 monitors, printers, and speakers. Output sent to a monitor is sometimes called softcopy, while output sent to a printer is called hardcopy. Disk drives, USB drives, and CD/DVD recorders can also be considered output devices because the CPU sends them information to be saved.
Software If a computer is to function, software is not optional. Everything that a computer does, from the time you turn the power switch on until you shut the system down, is under the control of software. There are two general categories of software: system software and application software. Most computer programs clearly t into one of these two categories. Let s take a closer look at each.
1.2 Computer Systems: Hardware and Software
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 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.
Checkpoint www.myprogramminglab.com 1.1
Why is the computer used by so many different people, in so many different professions?
1.2
List the ve 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 le-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?
7
8
Chapter 1 Introduction to Computers and Programming
1.3
Programs and Programming Languages C ON CE PT: 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 wellde ned 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 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 dif cult. In addition, each different type of CPU has its own machine language. If you wrote a machine language program for computer A and 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 les, and then use special software to convert their programs to machine language.
1.3 Programs and Programming Languages
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. N O TE: 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 speci c parts of the program. Program 1-1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// This program calculates the user's pay. #include using namespace std; int main() { double hours, rate, pay; // Get the number of hours worked. cout > hours; // Get the hourly pay rate. cout > rate; // Calculate the pay. pay = hours * rate; // Display the pay. cout > letter; cout sold; store3 -= sold; // Adjust store 3's inventory. // Display each store's current inventory. cout months; charges = months * ADULT; cout hours; // Determine the hours to charge for. hours = hours < MIN_HOURS ? MIN_HOURS : hours; // Calculate and display the charges. charges = PAY_RATE * hours; cout months; charges = months * ADULT; cout number; while (number < 1 || number > 100) { cout > number; }
This code rst allows the user to enter a number. This takes place just before the loop. If the input is valid, the loop will not execute. If the input is invalid, however, the loop will display an error message and require the user to enter another number. The loop will continue to execute until the user enters a valid number. The general logic of performing input validation is shown in Figure 5-4. Figure 5-4
Read the first value.
Is the value invalid? No
Yes
Display an error message.
Read another value.
239
240
Chapter 5 Loops and Files
The read operation that takes place just before the loop is called a priming read. It provides the rst value for the loop to test. Subsequent values are obtained by the loop. Program 5-5 calculates the number of soccer teams a youth league may create, based on a given number of players and a maximum number of players per team. The program uses while loops (in lines 25 through 34 and lines 41 through 46) to validate the user s input. Program 5-5 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 36 37 38 39 40 41 42 43 44 45 46 47
// This program calculates the number of soccer teams // that a youth league may create from the number of // available players. Input validation is demonstrated // with while loops. #include using namespace std; int main() { // Constants for minimum and maximum players const int MIN_PLAYERS = 9, MAX_PLAYERS = 15; // Variables int players, teamPlayers, numTeams, leftOver;
// // // //
Number Number Number Number
of of of of
available players desired players per team teams players left over
// Get the number of players per team. cout > teamPlayers; // Validate the input. while (teamPlayers < MIN_PLAYERS || teamPlayers > MAX_PLAYERS) { // Explain the error. cout value; cout using namespace std; int main () { string town; cout > town; cout > operator expects data to be delimited by whitespace characters.
59. T
F
The getline member function can be used to read text that contains whitespaces.
60. T
F
It is not possible to have more than one le open at once in a program.
61. T
F
Binary les contain unformatted data, not necessarily stored as text.
62. T
F
Binary is the default mode in which les are opened.
63. T
F
The tellp member function tells a le stream object which byte to move its write position to.
64. T
F
It is possible to open a le for both input and output.
ReviewProgramming Questions and Challenges Exercises
Find the Error Each of the following programs or program segments has errors. Find as many as you can. 65. fstream file(ios::in | ios::out); file.open("info.dat"); if (!file) { cout rectLength; // Store the width and length of the rectangle // in the box object. box.setWidth(rectWidth); box.setLength(rectLength); // Display the rectangle's data. cout setWidth(10.0); rectPtr->setLength(15.0); // Delete the object from memory. delete rectPtr; rectPtr = 0;
Line 2 de nes 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 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 modi cation 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.
725
726
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 106 107 108
//***************************************************** // Function main * //***************************************************** int main() { double number; double totalArea; Rectangle *kitchen; Rectangle *bedroom; Rectangle *den;
// // // // //
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; kitchen->setLength(number); cout > number; kitchen->setWidth(number); // Get the bedroom dimensions. cout > number; bedroom->setLength(number); cout > number; bedroom->setWidth(number); // Get the den dimensions. cout > number; den->setLength(number); cout > number; den->setWidth(number);
// Get the length // Store in kitchen object // Get the width // Store in kitchen object
// Get the length // Store in bedroom object // Get the width // Store in bedroom object
// 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
109 110 111 112 113 114 115 116 117 118 119 120 121 122 }
// Display the total area of the three rooms. cout rectLength; (program continues)
733
734
Chapter 13
Introduction to Classes
Program 13-4 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 > operator should not accept invalid dates. For example, the date 13/45/2012 should not be accepted. 9. FeetInches Modi cation Modify the FeetInches class discussed in this chapter so it overloads the following operators: = !=
Demonstrate the class s capabilities in a simple program. 10. Corporate Sales A corporation has six divisions, each responsible for sales to different geographic locations. Design a DivSales class that keeps sales data for a division, with the following members: * * *
*
An array with four elements for holding four quarters of sales figures for the division. A private static variable for holding the total corporate sales for all divisions for the entire year. A member function that takes four arguments, each assumed to be the sales for a quarter. The value of the arguments should be copied into the array that holds the sales data. The total of the four arguments should be added to the static variable that holds the total yearly corporate sales. A function that takes an integer argument within the range of 0 3. The argument is to be used as a subscript into the division quarterly sales array. The function should return the value of the array element with that subscript.
Write a program that creates an array of six DivSales objects. The program should ask the user to enter the sales for four quarters for each division. After the data are entered, the program should display a table showing the division sales for each quarter. The program should then display the total corporate sales for the year. Input Validation: Only accept positive values for quarterly sales gures. 11. FeetInches Class Copy Constructor and multiply Function Add a copy constructor to the FeetInches class. This constructor should accept a FeetInches object as an argument. The constructor should assign to the feet attribute the value in the argument s feet attribute, and assign to the inches
ReviewProgramming Questions and Challenges Exercises
attribute the value in the argument s inches attribute. As a result, the new object will be a copy of the argument object. Next, add a multiply member function to the FeetInches class. The multiply function should accept a FeetInches object as an argument. The argument object s feet and inches attributes will be multiplied by the calling object s feet and inches attributes, and a FeetInches object containing the result will be returned. 12. LandTract Class Make a LandTract class that is composed of two FeetInches objects, one for the tract s length and one for the width. The class should have a member function that returns the tract s area. Demonstrate the class in a program that asks the user to enter the dimensions for two tracts of land. The program should display the area of each tract of land and indicate whether the tracts are of equal size. 13. Carpet Calculator The West eld Carpet Company has asked you to write an application that calculates the price of carpeting for rectangular rooms. To calculate the price, you multiply the area of the oor (width times length) by the price per square foot of carpet. For example, the area of oor that is 12 feet long and 10 feet wide is 120 square feet. To cover that oor with carpet that costs $8 per square foot would cost $960. (12 * 10 * 8 = 960.) First, you should create a class named RoomDimension that has two FeetInches objects as attributes: one for the length of the room and one for the width. (You should use the version of the FeetInches class that you created in Programming Challenge 11 with the addition of a multiply member function. You can use this function to calculate the area of the room.) The RoomDimension class should have a member function that returns the area of the room as a FeetInches object. Next, you should create a RoomCarpet class that has a RoomDimension object as an attribute. It should also have an attribute for the cost of the carpet per square foot. The RoomCarpet class should have a member function that returns the total cost of the carpet. Once you have written these classes, use them in an application that asks the user to enter the dimensions of a room and the price per square foot of the desired carpeting. The application should display the total cost of the carpet. 14. Parking Ticket Simulator For this assignment you will design a set of classes that work together to simulate a police of cer issuing a parking ticket. The classes you should design are: *
The ParkedCar Class: This class should simulate a parked car. The class s responsibilities are: To know the car s make, model, color, license number, and the number of minutes that the car has been parked
867
868
Chapter 14
More About Classes
*
*
*
The ParkingMeter Class: This class should simulate a parking meter. The class s only responsibility is: To know the number of minutes of parking time that has been purchased The ParkingTicket Class: This class should simulate a parking ticket. The class s responsibilities are: To report the make, model, color, and license number of the illegally parked car To report the amount of the ne, which is $25 for the rst hour or part of an hour that the car is illegally parked, plus $10 for every additional hour or part of an hour that the car is illegally parked To report the name and badge number of the police of cer issuing the ticket The PoliceOfficer Class: This class should simulate a police officer inspecting parked cars. The class s responsibilities are: To know the police of cer s name and badge number To examine a ParkedCar object and a ParkingMeter object, and determine whether the car s time has expired To issue a parking ticket (generate a ParkingTicket object) if the car s time has expired
Write a program that demonstrates how these classes collaborate. 15. Car Instrument Simulator For this assignment you will design a set of classes that work together to simulate a car s fuel gauge and odometer. The classes you will design are: *
The FuelGauge Class: This class will simulate a fuel gauge. Its responsibilities are To know the car s current amount of fuel, in gallons. To report the car s current amount of fuel, in gallons. To be able to increment the amount of fuel by 1 gallon. This simulates putting fuel in the car. (The car can hold a maximum of 15 gallons.) To be able to decrement the amount of fuel by 1 gallon, if the amount of fuel is greater than 0 gallons. This simulates burning fuel as the car runs.
*
The Odometer Class: This class will simulate the car s odometer. Its responsibilities are: To know the car s current mileage. To report the car s current mileage. To be able to increment the current mileage by 1 mile. The maximum mileage the odometer can store is 999,999 miles. When this amount is exceeded, the odometer resets the current mileage to 0. To be able to work with a FuelGauge object. It should decrease the FuelGauge object s current amount of fuel by 1 gallon for every 24 miles traveled. (The car s fuel economy is 24 miles per gallon.)
Demonstrate the classes by creating instances of each. Simulate lling the car up with fuel, and then run a loop that increments the odometer until the car runs out of fuel. During each loop iteration, print the car s current mileage and amount of fuel.
CHAPTER
15
Inheritance, Polymorphism, and Virtual Functions
TOPICS 15.1 What Is Inheritance? 15.2 Protected Members and Class Access 15.3 Constructors and Destructors in Base and Derived Classes 15.4 Rede ning Base Class Functions 15.5 Class Hierarchies
15.1
15.6 Polymorphism and Virtual Member Functions 15.7 Abstract Base Classes and Pure Virtual Functions 15.8 Multiple Inheritance
What Is Inheritance? CO NCE PT: Inheritance allows a new class to be based on an existing class. The new class inherits all the member variables and functions (except the constructors and destructor) of the class it is based on.
Generalization and Specialization In the real world you can nd many objects that are specialized versions of other more general objects. For example, the term insect describes a very general type of creature with numerous characteristics. Because grasshoppers and bumblebees are insects, they have all the general characteristics of an insect. In addition, they have special characteristics of their own. For example, the grasshopper has its jumping ability, and the bumblebee has its stinger. Grasshoppers and bumblebees are specialized versions of an insect. This is illustrated in Figure 15-1.
869
870
Chapter 15
Inheritance, Polymorphism, and Virtual Functions
Figure 15-1 All insects have certain characteristics.
Insect
In addition to the common insect characteristics, the bumblebee has its own unique characteristics such as the ability to sting.
In addition to the common insect characteristics, the grasshopper has its own unique characteristics such as the ability to jump.
Inheritance and the Is a Relationship When one object is a specialized version of another object, there is an is a relationship between them. For example, a grasshopper is an insect. Here are a few other examples of the is a relationship. A poodle is a dog. A car is a vehicle. A tree is a plant. A rectangle is a shape. A football player is an athlete. When an is a relationship exists between classes, it means that the specialized class has all of the characteristics of the general class, plus additional characteristics that make it special. In object-oriented programming, inheritance is used to create an is a relationship between classes. Inheritance involves a base class and a derived class. The base class is the general class and the derived class is the specialized class. The derived class is based on, or derived from, the base class. You can think of the base class as the parent and the derived class as the child. This is illustrated in Figure 15-2. Figure 15-2 Insect class members
Base Class (Parent)
Grasshopper class members
Derived Class (Child)
15.1 What Is Inheritance?
The derived class inherits the member variables and member functions of the base class without any of them being rewritten. Furthermore, new member variables and functions may be added to the derived class to make it more specialized than the base class. Let s look at an example of how inheritance can be used. Most teachers assign various graded activities for their students to complete. A graded activity can receive a numeric score such as 70, 85, 90, and so on, and a letter grade such as A, B, C, D, or F. The following GradedActivity class is designed to hold the numeric score and letter grade of a graded activity. When a numeric score is stored by the class, it automatically determines the letter grade. (These les are stored in the Student Source Code Folder Chapter 15\ GradedActivity Version 1.)
Contents of GradedActivity.h (Version 1) 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
#ifndef GRADEDACTIVITY_H #define GRADEDACTIVITY_H // GradedActivity class declaration class GradedActivity { private: double score; // To hold the numeric score public: // Default constructor GradedActivity() { score = 0.0; } // Constructor GradedActivity(double s) { score = s; } // Mutator function void setScore(double s) { score = s; } // Accessor functions double getScore() const { return score; } char getLetterGrade() const; }; #endif
Contents of GradedActivity.cpp (Version 1) 1 2 3 4 5 6
#include "GradedActivity.h" //****************************************************** // Member function GradedActivity::getLetterGrade * //******************************************************
871
872
Chapter 15
Inheritance, Polymorphism, and Virtual Functions
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
char GradedActivity::getLetterGrade() const { char letterGrade; // To hold the letter grade if (score > 89) letterGrade = else if (score > letterGrade = else if (score > letterGrade = else if (score > letterGrade = else letterGrade =
'A'; 79) 'B'; 69) 'C'; 59) 'D'; 'F';
return letterGrade; }
The GradedActivity class has a default constructor that initializes the score member variable to 0.0. A second constructor accepts an argument for score. The setScore member function also accepts an argument for the score variable, and the getLetterGrade member function returns the letter grade that corresponds to the value in score. Program 15-1 demonstrates the GradedActivity class. (This le is also stored in the Student Source Code Folder Chapter 15\GradedActivity Version 1.) Program 15-1 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
// This program demonstrates the GradedActivity class. #include #include "GradedActivity.h" using namespace std; int main() { double testScore;
// To hold a test score
// Create a GradedActivity object for the test. GradedActivity test; // Get a numeric test score from the user. cout > testScore; // Store the numeric score in the test object. test.setScore(testScore); // Display the letter grade for the test. cout length; // 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 > (stream extraction), 86 87, 275, 277, 280, 579 [ ] (array subscript operator), 428 430, 579
A abs library function, 127 abstract array data type case study, 770 774 abstract base classes, 921 925 abstract data type (ADT)
in STL, 983 984 and structures, 593 595 abstraction, 593 access speci ers base class, 874 875 in class declarations, 712 713 accessors, 716 717 accumulator, 257 259 actual arguments, 313 actual parameters, 313 addition operator (+), 61, 62, 92 94, 579 address, memory, 5, 396, 491 address operator (&), 491 493 ADT, see abstract data type aggregation, 849 852 has-a relationship, 851 in UML diagrams, 852 853 algebraic expressions, 94, 95 algorithm, 8 exhaustive, 1130 1132 factorial, 1106 1109 QuickSort, 1125 1129 search, 451 464, 480 485 sorting, 464 485 STL, 984 986, 990 996 Alice software, 1167 1193 adding objects, 1172 1175 camera controls, 1175 copying/deleting instructions, 1187 creating methods, 1187 1188 creating variables/parameters, 1188 1190 creating world, 1172 deleting objects, 1180 downloading/installing, 1167 environment, 1169 1170 events, 1191 1193 modifying objects, in Scene Editor mode, 1180 1182
1201
1202
Index
Alice software (continued) playing world, 1171 primitive methods, 1177 1180 properties, 1176 1177 renaming methods, 1188 selecting objects, 1176 single view/quad view modes, 1182 1183 variable assignment, 1191 Welcome to Alice! dialog box, 1167 1169 writing methods, 1183 1186 ALU, 4 AND & bitwise operator, see Appendix J on the book s companion Web site && logical operator, 182 185, 188 189 anonymous enumerated type, 630 631 anonymous unions, 625 627 append member function, string class, 582 application software, 6, 7 arguments, 95 96, 313 317 arrays as, 405 414, 419 421 command-line, see Appendix H on the book s companion Web site default, 347 350 passing, with pointers, 572 573 structures as, 612 615 arithmetic and logic unit (ALU), 4 arithmetic assignment operators, 108 arithmetic expressions, 91 98 arithmetic operators, 60 67 array subscript operator ([ ]), 428 430, 579 arrays, 377 438, 451 485 accessing elements, 379 386 assigning one, to another, 396 397 averaging values in, 398 binary search, 454 457 bounds checking, 386 388 bubble sort, 465 468 C-strings in, 550 552 comparing, 401 402 Demetris Leadership Center case study, 458 464, 472 480 described, 377 378 duplicating, 525 527 enum with, 631 633 as function arguments, 405 414, 419 421 highest and lowest values, 398 399 initialization, 389 394, 418 419, 608, 760 linear search, 451 454 linked lists vs., 1003 1004 memory requirements, 378 379
National Commerce Bank case study, 424 426 of objects, 759 761 parallel, 402 403 partially lled, 399 401 and pointers, 500 504 printing contents of, 397 processing contents of, 394 402 search algorithms, 451 464, 480 485 selection sort, 469 472 sorting algorithms, 464 485 structure, 605 608 summing values in, 397 398, 421 423 three or more dimensions, 423 two-dimensional, 416 423 and vectors, 427 438, 480 485 arrow operator (->), 618 619, 621, 622, 724 ascending order, sorting in, 465 ASCII, 47, 195, 1195 1196 assign member function, string class, 582 assignment combined, 107 110 memberwise, 812 813 multiple, 107 assignment operator (=), 15, 38 39, 58, 161 162, 237, 579 assignment statement, 38 39, 58 associative containers, 427, 983, 984 associativity, 93 94, 150, 188 189, 1197 at member function string class, 582 vector, 437, 989 atof library function, 563, 564 atoi library function, 563, 564 atol library function, 563, 564 attributes, 706 averages in arrays, 398 calculating, 97 98
B back member function, list, 1035 bad member function, le stream, 662 bad_alloc exception, 965 966 base case, recursion, 1106 base class, 870 abstract, 921 925 multiple, 928 932 base class access speci cation, 874 875, 882 883 base class functions, rede ning, 896 901 base class pointers, 915 917 BASIC, 10
begin member function iterator, 989 string class, 582 vector, 989 bidirectional iterators, 984 binary digit (bit), 5, see also Appendix J on the book s companion Web site binary les, 267, 674 679 binary numbers, 8, see also Appendix J on the book s companion Web site binary operator, 60 binary search, 454 457 ef ciency, 457 recursive version, 1119 1121 binary trees, 1137 1163 applications of, 1139 1140 child nodes, 1137 creating, 1141 1142 deleting a node, 1148 1157 described, 1137 1138 inorder traversal, 1144 1147 inserting a node, 1142 1144 leaf nodes, 1137 NULL address, 1137 operations, 1140 1157 postorder traversal, 1144 1147 preorder traversal, 1144 1147 root node, 1137 search trees, 1139 searching for a value in, 1144 1147 subtrees, 1138 templates for, 1157 1163 traversing, 1144 1147 tree pointer, 1137 binary_search algorithm (STL), 984, 990 991 binding, 909 dynamic, 909 static, 909 bit, 5, see also Appendix J on the book s companion Web site bitwise operators, see Appendix J on the book s companion Web site block scope, 212 blocks, of code, 164, 211 214, 236 237 blueprints, classes as, 709 710 body of function, 303 of loop, 233 bool, 56 and ags, 181 returning, from a function, 334 336 Boole, George, 56 Boolean expression, 56, 150 bounds checking, for arrays, 386 388 braces, 29, 30, 164, 165, 236 237 break statement, 204, 205, 285 286
Index
bubble sort, 465 468 buffer, keyboard, 89 byte, 5
C C#, 10 C programming language, 9 11, 105 106 C++ programming language, 10, 11, 27 76 arithmetic operators, 60 67 bool data type, 56 char data type, 47 51 comments, 68 70 cout object, 31 36 oating-point data types, 53 56 identi ers, 41 42 #include directive, 36 37 initialization, 58 59 integer data types, 42 47 named constants, 70 72 parts of program, 27 31 programming style, 72 74 scope, 59 60 sizeof operator, 57 standard and prestandard, 74 76 string class, 51 52 variables and literals, 37 40, 58 59 C-strings, 548 573 in arrays, 550 552 comparing, 558 561 concatenation, 553 556 copying, 554 556 described, 548 549 lenames as, 283 handling functions, 568 573 length of, 552 553 library functions, 552 562 and null terminators, 548 549 numeric conversion functions, 563 568 searching within, 556 558 and string literals, 549 550 calling a function, 95, 304 309, 328 331 capacity member function string class, 582 vector, 437, 989 capitalization, of variable names, 42 case conversion, character, 545 547 case statement, 203 204 case study abstract array data type, 770 774 Demetris Leadership Center, 458 464, 472 480 dollarFormat function, 584 585 General Crates, Inc., 132 136 Home Software Company, 584 585, 763 770
National Commerce Bank, 424 426 United Cause, 529 534 catch block, 949 catch key word, 949 CD, 6 central processing unit (CPU), 3, 4 char, 47 51 character case conversion, 545 547 tolower function, 545 toupper function, 545 character literals, 48 51 character testing, 541 545 isalnum function, 542 isalpha function, 542 isdigit function, 542 islower function, 542 isprint function, 542 ispunct function, 542 isspace function, 542 isupper function, 542 characters, 541 547 character literals, 48 51 comparing, 195 196 converting cases, 545 547 inputting, 122 and string objects, 120 126 whitespace, 120 121 cin, 18, 85 89 entering multiple values, 87 89 get member function, 123 124 getline member function, 121 122, 551, 566 567 ignore member function, 125 126, 566 inputting characters, 122 inputting characters with, 120 121 keyboard buffer, 89 width member function, see Appendix L on the book s companion Web site circularly linked list, 1034 class implementation le, 730 class speci cation le, 729 class templates, 973 982 de ning objects of, 977 979 and inheritance, 979 982 linked list, 1028 1033 type parameter, 974 classes, 705 785, 799 857, 869 932 and abstract array data types, 770 774 abstract base, 921 925 access speci ers, 712 713 accessors, 716 717, 740 741 aggregation, 849 853 arguments to constructors, 742 750 arrays of class objects, 759 761
1203
base, 870 as blueprint, 709 710 collaborations, 853 857 const member functions, 714, 717 constructor overloading, 754 757 constructors, 738 750, 884 895 conversion of class objects, 846 848 copy constructor, 813 818 and data hiding, 717 declaration statements, 712, see also Appendix K on the book s companion Web site default constructor, 742, 749 751
de ning class objects, 717 727 derived, 870 871 described, 712 destructors, 750 753, 884 885 dot operator (.), 718 719 dynamically allocated objects, 724 727 nding, 777 785 forward declaration, 809 friend functions, 807 811 getter function, 716 has-a relationship, 851 hierarchies of, 901 907 Home Software Company case study, 763 770 implementation le, 730 include guard, 730 731 inheritance, 869 877, 928 932 inline member functions, 735 737 instance and static members, 799 807 is-a relationship, 870 877, 918 member functions, de ning, 715 716 memberwise assignment, 812 813 multiple inheritance, 928 932 mutators, 716 objects vs., 708 710 operator overloading, 819 846 overloading member functions, 751 placement of public and private members, 714 715 pointers, 724 727 polymorphism, 907 921 private member functions, 758 759 private members, 713 714, 728 729 problem domain, 778 and procedural/object-oriented programming, 705 711 protected members and class access, 878 884
1204
Index
classes (continued) public member functions, 713 714 public members, 713 714 rede ning base class functions, 896 901 responsibilities of, 777 785 scope resolution operator (::), 716 setter function, 716 speci cation and implementation, 729 735 stale data, avoiding, 724 templates, 973 984 this pointer, 823 824 and UML, 774 777 virtual functions, 909 913 whole-part relationship, 851 clear member function le stream objects, 662 string class, 582 vector, 434 435, 437, 990 close member function, le stream objects, 270 closing a le, 269 270 cmath header le, 96, 127 COBOL, 10 code reuse, 302 coercion, 101 collaborations, class, 853 857 columns, of arrays, 416, 417, 422 423 combined assignment operators, 107 110 coming into scope, 213 command-line arguments, see Appendix H on the book s companion Web site comments, 27, 68 70 //, 68 69 /* */, 69 70 multi-line, 69 70 single line, 68 69 compact disc (CD), 6 compare member function, string class, 583 compiler, 11, 12, 652 compound operators, 108 computer games, 265 concatenation, 126, 553 556 conditional expressions, 199 201 conditional loops, 247 conditional operator, 199 201 conditionally-executed code, 155 156, 162 165, 233 conditions, testing, 173 175 console, 31, 86 console output, 31 const, 513 515, 517 as array parameter, 410 copy constructors, 816 818 member functions, 714, 717
constant pointers, 516 517 constant reference parameters, 633 constants global, 340 342 named, 70 72 pointers to, 513 515, 517 constructors, 738 750 arguments passed to, 742 750 in base and derived classes, 884 895 copy, 813 818 default, 742, 749 751 default arguments with, 748 749 overloading, 754 757 containers, 983 associative, 427, 983, 984 sequence, 427, 983 STL, 427 continue statement, 286 288 control unit, 4 conversion data type, 100 101 object, 846 848 string/numeric, 563 568 by type casting, 103 106 cookies, 265 copy constructors, 813 818 const parameters in, 816 818 default, 818 and function parameters, 818 copy member function, string class, 583 cos library function, 127 count algorithm (STL), 985, 992 993 count-controlled loops, 247, 255 256 counters, 241 242 cout, 18, 29, 31 36 fixed manipulator with, 116 118 left manipulator with, 118 119 precision member function, see Appendix L on the book s companion Web site right manipulator with, 118 119 setf member function, see Appendix L on the book s companion Web site setprecision manipulator with, 114 116, 119 setw manipulator with, 112 113, 119 showpoint manipulator with, 118, 119 unsetf member function, see Appendix L on the book s companion Web site width member function, see Appendix L on the book s companion Web site
CPU, 3, 4 CRC cards, 856 857 cstdlib header le, 129, 361, 563 cstring header le, 552 ctime header le, 129
D data hiding, 706 707, 717 data types, 42 57 abstract, 593 595 bool, 56 char, 47 51 coercion, 101 conversion, 100 101, 103 106 demotion, 101 double, 53 55 enumerated, 627 637 float, 53 56 oating-point, 53 56 generic, 967 int, 43 44 integer, 42 46 long, 43 44 long double, 53 54 numeric, 42 43 primitive, 594 promotion, 101 ranking, 100 101 short, 43 44 size of, determining, 57 type casting, 103 106 unsigned int, 43 44 unsigned long, 43 44 unsigned short, 43 44 database management systems, 651 debugging desk-checking, 21 hand-tracing, 130 132 stubs and drivers, 363 365 decimal point, digits displayed after, 114 118 decision making, 149 214 blocks and scope, 211 214 checking numeric ranges, 189 comparing characters and strings, 195 198 conditional execution, 162 165 conditional operator, 199 201 ags, 181 182 if/else if statements, 176 180 if/else statements, 166 168 if statements, 154 165 logical operators, 182 189 menus, 190 193 nested if statements, 169 175 relational operators, 149 153 switch statement, 202 209 validating user input, 193 194 decision structure, 154
Index
declaration, 17 decode, 4 decrement operator (--), 227 232 in mathematical expressions, 231 post x and pre x modes, 228 231 in relational expressions, 231 232 default arguments, 347 350, 748 749 default constructors, 742, 749 751 default copy constructor, 818 default statement, 203 204 #define directive, 75 76, 731 de nitions, variable, 17, 37 38, 59, 211 213 delete operator, 520 Demetris Leadership Center case study, 458 464, 472 480 demotion, data type, 101 depth of recursion, 1103 deque (STL type), 983, 1093 1094 front member function, 1093 pop_front member function, 1093 push_back member function, 1093 dequeue operation, 1073 1076 dereferencing, of pointers, 497 derived class, 870 descending order, sorting in, 465 designing programs, 18 22 desk-checking, 21 destructors, 750 753 base and derived classes, in, 884 895 virtual, 918 921 digital versatile disc (DVD), 6 digits, after decimal point, 114 118 direct access les, 267 direct recursion, 1112 directive, preprocessor, 28, 36 disk drive, 5 6 divide and conquer approach, 301 302 division integer, 61, 63, 66 67, 101 remainder of, 61 by zero, 167, 947 948 division operator (/), 61, 92 94 do-while loop, 242 246, 262 with menus, 244 246 as posttest loop, 242 244 dollarFormat function case study, 584 585 dot operator (.), 598, 622, 718 719 double, 53 55 double precision, 53 54 doubly linked list, 1034 drivers, 363 365 dummy parameter, 832 DVD, 6
dynamic binding, 909 dynamic memory allocation, 518 522 bad_alloc exception, 965 966 objects, 724 727, 742, 753 for structures, 620 621 dynamic queues, 1073, 1085 1092 dynamic stacks, 1044, 1060 1070
E E notation, 53, 54 EBCDIC, 47 editor, text, 11 12 ef ciency binary search, 457 linear search, 454 elements (array) accessing, 379 386 described, 378 processing, 394 402 removing, from vectors, 433 434 elements (language), 13 15 else in if/else statement, 167 trailing, 177 179 empty member function list, 1035 string class, 583 vector, 435 437, 990 encapsulation, 706 end member function iterator, 989 list, 1035 string class, 583 vector, 990 end of a le, detecting, 279 281 end-of- le marker, 654 #endif directive, 730 731 endl, 33 enqueue operation, 1073 1076 enum, 627 637 anonymous, 630 631 with arrays, 631 633 assigning, to int variables, 629 assigning integers to enum variables, 628 629 comparing enumerators, 629 630 declaration and de nition, 637 de ning, 628 629 math operators with, 631 outputting values with, 633 635 and scope, 636 specifying values, 635 636 enumerated data types, 627 637, see also enum enumerators, 628 630, 636 eof member function, le stream, 662 equal-to operator (==), 150 152, 161 162, 237 erase member function
1205
list, 1035 string class, 583 vector, 990 error testing, les, 281 283, 662 664 errors le open, 281 283 logical, 21 off-by-one, 388 recovering from, 958 960 syntax, 11 and trailing else, 178 179 escape sequences, 34 36 \\, 35 \', 35 \", 35 \a, 35 \b, 35 \n, 34 35 \r, 35 \t, 35 newline, 34 exceptions, 519, 947 966 bad_alloc, 965 966 catch block, 949 dynamic memory allocation, 519 exceptions handler, 948 extracting data from, 960 964 handling, 949 951 memory allocation error, 965 966 multiple, handling, 954 958 new operator, 519 not catching, 951 object-oriented handling, 951 954 recovering from errors, 958 960 rethrowing, 964 965 throw key word, 948 throw point, 948 throwing, 948 try block, 949 try/catch construct, 949 951 unwinding the stack, 964 exception handler, 948 exclusive OR, bitwise, see Appendix J on the book s companion Web site executable code, 11 12 executable le, 11 execute, 4 exhaustive algorithms, 1130 1132 exit() library function, 360 362 exit code, 361 EXIT_FAILURE constant, 361 EXIT_SUCCESS constant, 361 exp library function, 127 exponents, 95 97 expressions, 85 136, 91 algebraic, 94, 95 arithmetic, 91 98 Boolean, 56, 150 C-style and prestandard C++ forms, 105 106
1206
Index
expressions (continued) characters and string objects, 120 126 cin object, 85 89 conditional, 199 201 formatting output, 111 119 and hand tracing programs, 130 136 initialization, 248, 252 256 mathematical, 91 98, 231 and mathematical library functions, 127 130 multiple and combined assignment, 107 110 over ow and under ow, 102 103 relational, 150, 231 232 test, 248 type casting, 103 105 type conversion, 100 101 update, 248, 252 256 of while loop, 233
F factorial algorithm, 1106 1109 fail member function, le stream, 662 fallthrough capability, of switch statement, 205 207 false values, 150, 152 153, 160 161 fetch, 4 fetch/decode/execute cycle, 4 Fibonacci numbers, 1114 1116 eld, bit, see Appendix J on the book s companion Web site eld width, 112 FIFO ( rst-in rst out), 1073 le access ags, 653 ios::app, 653 ios::ate, 653 ios::badbit, 662 ios::binary, 653 ios::eofbit, 662 ios::failbit, 662 ios::goodbit, 662 ios::hardfail, 662 ios::in, 653 ios::out, 653 ios::trunc, 653 le buffer, 269 le open errors, 281 283 le operations, 651 695 append mode, 653 binary les, 674 679 described, 651 652 end-of- le marker, 654 fstream data type, 652 656 member functions for reading and writing, 665 671 open modes of ifstream and ofstream, 656
opening les for input and output, 691 695 opening les with de nition statements, 657 opening multiple les, 672 674 random-access les, 683 691 reading a character, 669 670 reading a line, 666 records with structures, 679 683 rewinding, 690 691 writing a character, 670 671 le stream objects, 268 closing, 269 270 creating, 268 269 member functions, 665 671, see also Appendix L on the book s companion Web site passing to functions, 660 661 lename extensions, 267 268 lenames and le stream objects, 267 268 user-speci ed, 283 284 les, see also speci c types closing, 269 270 for data storage, 265 274 detecting end of, 279 281 le open errors, 281 283 input/output program, 268 opening, and creating le objects, 268 269 processing, with loops, 278 281 read position, 275 276 reading from, 265 268, 275 278, 384 385 user-speci ed lenames, 283 284 writing from, 385 386 writing to, 265, 266, 270 274 fill member function, 262 lters, 672 find algorithm (STL), 985, 994 995 find member function, string class, 583 nding classes, 777 785 rst-in rst out (FIFO), 1073 fixed manipulator, 116 118, 658 xed-point notation, 116 117 ags, 181 182 ash memory, 6 float, 53 56 oating-point data types, 53 56 comparing, 159 160 and integer variables, 55 56 oating-point literals, 54 oating-point notation, 114 116, 118 oppy disk drive, 6 owcharts, 20, see also Appendix D on the book s companion Web site fmod library function, 127 for loops, 247 256, 262 and arrays, 382
initialization expression, 248, 252 256 omitting expressions of, 254 256 as pretest loop, 251 test expression, 248 update expression, 248, 252 256 user-controlled, 252 253 while and do-while vs., 250 251 for_each algorithm (STL), 985, 995 996 formal arguments, 313 formatting output, 111 119, 658 659 FORTRAN, 10 forward declaration, 809 forward iterators, 984 friend class, 811 friend functions, 807 811 friend key word, 807 front member function deque, 1093 list, 1035 vector, 990 fstream header le, 268 fstream objects, 653 function arguments, 95 96 le stream objects as, 660 661 structures as, 612 615 function call statements, 304 function declarations, 311 function header, 303 function parameters pointers as, 509 517 reference variables as, 350 354 function prototypes, 311 312 function signature, 357 function templates, 966 973 with multiple types, 970 971 overloading with, 971 972 using operators in, 970 functions, 29, 301 365 bool value, returning, 334 336 calling, 95, 304 309, 328 331 default arguments, 347 350, 748 de ning, 303 304 exit(), 360 362 friend, 807 811 generic, 966 inline, 735 737 local and global variables, 327, 336 346 main, 29, 304 member, 706 modular programming, 301 302 overloading, 356 360 overriding, 918 passing, by reference, 509 passing data by value, 318 319 pointers, returning, 522 527 pure virtual, 921 925
Index
recursive, 1101 1105 rede ning base class, 896 901 reference variables as parameters, 350 354 return statement, 324 325, 327 sending data into, 313 317 static local variables, 344 346 static member, 804 807 string handling, 568 573 structures, returning, 615 617 stubs and drivers, 363 365 value-returning, 326 336 virtual, 909 913, 921 925 void, 303 304
G g++ command, 11 games, computer, 265 GCD (greatest common divisor), 1113 1114 General Crates, Inc. case study, 132 136 generalization, inheritance and, 869 870 generic data types, 967 generic functions, 966 get member function cin, 123 124 le streams, 669 670 getline member function cin, 121 122, 551, 566 567 le streams, 666 669 getter functions, 716 global constants, 340 342 global variables, 338 340, 343, see also Appendix K on the book s companion Web site good member function, le stream, 662 greater-than operator (>), 150 152 greater-than or equal-to operator (>=), 150 152 greatest common divisor (GCD), 1113 1114
H hand-tracing, 130 132 handler, exception, 948 Hanoi, Towers of, 1122 1125 hardware, 3 6 CPU, 3, 4 input devices, 3, 6 main memory, 3, 5 output devices, 3, 6 secondary storage, 3, 5 6 has-a relationship, 851 header function, 303 loop, 233, 248 header le, 28, see also Appendix I on the book s companion Web site
cmath, 96, 127 cstdlib, 129, 361, 563 cstring, 552 ctime, 129 fstream, 268 iomanip, 118 iostream, 28, 36 37 prestandard style, 74 string, 51, 574 hexadecimal literals, 46 hiding data, 706 707, 717 hierarchies, class, 901 907 hierarchy chart, 20 high-level languages, 9 Hoare, C.A.R., 1125 Home Software Company case study, 584 585, 763 770
I IDE, 12 identi ers, 41 42 capitalization, 42 legal, 42 if/else if statement, 176 180 nested decision structures vs., 179 180 trailing else, 177 179 if/else statement, 166 168 if statement, 154 165 conditionally-executed code, 155 156, 162 165 expanding, 162 165 oating-point comparisons, 159 160 nested, 169 175, 179 180 programming style, 159 semicolon in, 158 #ifndef directive, 730 731 ifstream objects, 268, 656 >> with, 275 close member function, 270 open member function, 269 ignore member function, cin, 125 126, 566 image editors, 265 implementation le, class, 730 implicit sizing, of arrays, 393 394 #include directive, 28, 36 37, 730 include le directory, 733 include guard, 730 731 increment operator (++), 227 232 in mathematical expressions, 231 post x and pre x modes, 228 231 in relational expressions, 231 232 indentation, 72 73, 159, 237 indirect recursion, 1112 indirection operator (*), 497 499 in nite loop, 236 inheritance, 869 877 base class, 870
class hierarchies, 901 907 and class templates, 977 979 constructors and destructors, 884 895 derived class, 870 871 is-a relationship, 870 877 multiple, 928 932 rede ning functions, 896 901 initialization, 59 array, 389 394, 418 419, 608, 760 partial array, 392 393 pointers, 506 structure, 602 604 structure array, 608 variable, 59 vector, 428 initialization expression, for loop, 248, 252 256 initialization list, 390 inline expansion, 737 inline member functions, 735 737 inorder traversal, binary trees, 1144 1147 input, 17 18 array contents, 381 384 with cin, 85 89 reading, into string objects, 576 input devices, 6 input les, 266 input iterators, 984 input validation and decision making, 193 194 and while loop, 239 241 input output stream library, 36 insert member function list, 1035 string class, 583 vector, 990 instances of classes, 717 727 of structures, 598 of variables, 799 801 instantiation, 717 int, 43 44, 629 integer data types, 42 46 integer division, 61, 63, 66 67, 101 integer literals, 45 46 IntegerList class, 770 774 integrated development environment (IDE), 12 iomanip header le, 118 ios::app access ag, 653 ios::ate access ag, 653 ios::badbit status ag, 662 ios::binary access ag, 653, 675 ios::eofbit status ag, 662 ios::failbit status ag, 662 ios::goodbit status ag, 662
1207
1208
Index
ios::hardfail status ag, 662 ios::in access ag, 653 ios::out access ag, 653 iostream header le, 28, 36 37 ios::trunc access ag, 653 is-a relationship, 870 877, 918 isalnum library function, 542 isalpha library function, 542 isdigit library function, 542 islower library function, 542 isprint library function, 542 ispunct library function, 542 isspace library function, 542 isupper library function, 542 iteration, loop, 234 iterators, 983 [ ] operator, 987 989 begin member function, 989 end member function, 989 itoa library function, 563 565
J Java, 10 JavaScript, 10
K key words, 14 15, 41 42 keyboard buffer, 89 keyboard input, with cin, 85 89
L language elements, 13 15 last-in- rst-out (LIFO), 1043 leaving scope, 213 left manipulator, 118 119 legacy code, 550 length, of C-strings, 552 553 length member function, string class, 580 581, 583 less-than operator ( (structure pointer), 618 619, 621, 622 !, 182, 187 189, 560 !=, 150 152 %, 61, 63, 66 67, 93, 94 %=, 108 110 & (address), 491 493 &&, 182 185, 188 189 * (indirection), 497 499 * (multiplication), 15, 61, 62, 92 95 * (pointer variable declaration), 496, 621 622 *=, 108 110 . (dot operator), 598, 622, 718 719 /, 61, 92 94 /=, 108 110 ?: (conditional), 199 201 ||, 182, 185 186, 188 189 +, 61, 62, 92 94, 579 ++, 227 232 +=, 108 110, 579 , 86 87, 275, 277, 280, 579 [ ] operator, 428 430, 579 arithmetic, 60 67 associativity, 93 94, 150, 188 189, 1197 binary, 60 bitwise, see Appendix J on the book s companion Web site combined assignment, 107 110 conditional, 199 201 delete, 520 logical, 182 189 new, 518 522 overloading, 819 846 precedence of, 92 93, 188 189, 1197 relational, see relational operators scope resolution (::), 716 sizeof, 57 string class, 126, 579 ternary, 60, 199 unary, 60
OR ^ bitwise exclusive, see Appendix J on the book s companion Web site | bitwise operator, see Appendix J on the book s companion Web site || logical operator, 182, 185 186, 188 189 output, 18 array contents, 381 384 with enum, 633 635 formatting, 111 119, 658 659 output devices, 6 output les, 265 output iterators, 984 over ow, 102 103 overhead, 1106 overloading functions, 356 360 constructors, 754 757 member functions, 751 templates, 971 972 overriding, 918
P parallel arrays, 402 403 parameter lists, 303 parameters, 313, 316 317 array, 410 constant reference, 633 pointers as, 509 517 reference variables as, 350 354, 509 parentheses, 30, 94, 201 partially lled arrays, 399 401 Pascal, 10 passing by reference, 350 354, 509 passing by value, 318 319, 633 passing to functions arrays, 405 414 with pointers, 572 573 two-dimensional arrays, 419 421 percentage, 63 64 percentage discounts, 64 65 pointers, 491 534 address operator (&), 491 493 arithmetic with, 504 505 and arrays, 500 504 base class, 915 917 comparing, 507 509 constant, 516 517 to constants, 513 515, 517 creating and using, 493 500 dynamic memory allocation, 518 522 as function parameters, 509 517 initializing, 506 to objects, 724 727 passing C-string arguments with, 572 573 returning, from a function, 522 527
structure pointer operator, 618 619, 621, 622 to structures, 618 621 structures containing, 683 United Cause case study, 529 534 polymorphism, 907 921 abstract base classes, 921 925 base class pointers, 915 917 dynamic binding, 909 overriding, 918 pure virtual function, 921 925 and references or pointers, 913 915 static binding, 909 virtual destructors, 918 921 virtual functions, 909 913, 921 925 pop operation (stacks), 1044 1045 pop_back member function list, 1035 vector, 433 434, 437, 986 pop_front member function deque, 1093 list, 1035 portability, of C++, 11 post x mode, 228 231 postorder traversal, binary trees, 1144 1147 posttest loop, 242 244 pow function, 95 97, 128 power, raising a number to, 95 97 precedence, operator, 92 93, 188 189, 1197 precision, 114 precision member function, cout, see Appendix L on the book s companion Web site pre x, template, 967, 973 974 pre x mode, 228 231 preorder traversal, binary trees, 1144 1147 preprocessor, 11, 12 preprocessor directive, 28, 36 prestandard C++ standard vs., 74 76 type cast expressions, 105 106 pretest loops, 235, 251 priming read, 240 primitive data types, 594 private member functions, 758 759 private members, class, 713 715, 728 729 problem domain, 778 procedural programming, 22 23, 705 706 processing, 18 programmability, of computers, 1 2 programmer-de ned data types, 427 programmer-de ned identi ers, 14, 15 programmers, 2
Index
programming, 1 23 computer systems, 3 7 input, processing, and output, 17 18 procedural and object-oriented, 22 23 process of, 18 22 program elements, 13 17 programability of computers, 1 2 programs and progamming languages, 8 12 programming languages, 8 11, see also speci c languages high-level, 9 low-level, 9 programming process, 18 22 programming style, 72 73 and if statements, 159 and nested decision structures, 172 173 and while loops, 237 238 programs described, 1, 8 9 elements, 13 17 promotion, data type, 101 prompt, 86 protected members, 878 884 prototypes, function, 311 312 pseudocode, 20 21 public member functions, 713 714 public members, class, 713 715 punctuation, 14, 15 pure virtual function, 921 925 push operation (stacks), 1044 push_back member function deque, 1093 list, 1035 vector, 430 432, 438, 986 push_front member function, list, 1035 put member function, le streams, 670 671 Python, 10
Q queue (STL type), 1094 1095 queues, 1073 1095 applications of, 1073 array-based, 1076 1080 crawling problem with array, 1075 1076 dequeuing, 1073 1076 described, 1073 dynamic, 1073, 1085 1092 empty, detecting, 1076 enqueuing, 1073 1076 rst-in rst-out, 1073 full, detecting, 1076 linked list-based, 1085 1088 operations, 1073 1076
static, 1073, 1076 1084 STL queue and dequeue containers, 1092 1095 QuickSort algorithm, 1125 1129
R RAM, 5, 16 rand library function, 129 130 random-access les, 267, 683 691 random-access iterators, 984 random-access memory (RAM), 5, 16 random numbers, 129 130 limiting the range of, 130 seeding, 129 time function with, 129 random_shuffle algorithm (STL), 986, 990 991 ranges, numeric, 189 ranking, of data types, 100 101 read, priming, 240 read member function, le stream objects, 676 677 read position, of les, 275 276 reading data, from le, 266 records, 679 683 recursion, 1101 1133 base case, 1106 binary search, 1119 1121 counting characters, 1110 1112 depth of, 1103 direct, 1112 exhaustive algorithms, 1130 1132 factorial algorithm, 1106 1109 Fibonacci numbers, 1114 1116 greatest common divisor (GCD), 1113 1114 indirect, 1112 in nite, 1102 iteration vs., 1132 1133 linked list operations, 1116 1119 problem solving with, 1106 1112 QuickSort algorithm, 1125 1129 recursive functions, 1101 1105 recursively de ned problems, 1114 1116 Towers of Hanoi, 1122 1125 recursive case, 1106 rede ning base class functions, 896 901, 918 reference, passing by, 350 354, 509 reference parameters, constant, 633 reference variables as parameters, 350 354, 509 pointers vs., 494 495 reinterpret_cast, 677 relational expressions, 150, 231 232 relational operators, 149 153 and characters, 195 196 and pointers, 507 509 and string class, 196 198, 597
1211
relationships has-a, 851 is-a, 870 877, 918 whole-part, 851 remainder, of division, 61 replace member function, string class, 583 reserved words, 14 15 resize member function string class, 583 vector, 438, 990 responsibilities, identifying, 783 785 rethrowing an exception, 964 965 return statement, 30, 324 325, 327 return type, of functions, 303 returning bool value from functions, 334 336 pointers from functions, 522 527 structures from functions, 615 617 values from functions, 326 336 reusability, object, 708 reuse, code, 302 reverse member function list, 1036 vector, 438, 990 rewinding a le, 690 691 right-justi ed outputs, 112 right manipulator, 118 119 rows, of arrays, 416, 417, 421 422 Ruby, 10 running, of programs, 4 running total, 257 259 runtime library, 11 rvalue, 58
S scienti c notation, 53, 54 scope, 59 60, 211 213 block, 212 coming into, 213 leaving, 213 local, 212 scope resolution operator (::), 716 search algorithm, 451 464, 480 485 binary search, 454 457, 1119 1121 Demetris Leadership Center case study, 458 464 linear search, 451 454 for STL vector, 480 485 search trees, binary, 1139 secondary storage, 5 6 seekg member function, le stream objects, 683 688 seekp member function, le stream objects, 683 688 selection sort, 469 472 self-referential data structure, 1005
1212
Index
semicolon, 15, 30, 158, 258 sentinels, 260 262 sequence containers, 427, 983 sequence structure, 154 sequential le access, 267, 683 sequential search, 451 set (STL type), 984 setf member function, cout, see Appendix L on the book s companion Web site setprecision manipulator, 114 116, 119, 658 setter functions, 716 setw manipulator, 112 113, 119, 659 shadowing, of variables, 343, 349 short, 43 44 short-circuit evaluation, 183, 185 showpoint manipulator, 118, 119 signature, function, 357 signi cant digits, 114 sin library function, 127 single line comments, 68 69 single precision, 53 54 singly-linked list, 1034 size declarators, of arrays, 378, 380 size member function list, 1036 string class, 583 vector, 432 433, 986 sizeof operator, 57 sizing, of arrays, 392 393 software, 2, 6 7 application, 6, 7 system, 6 7 software developers, 2 software development tools, 7 software engineering, 22 sort algorithm (STL), 986, 990 991 sorting, of strings, 560 561, 576 578 sorting algorithm, 464 485 bubble sort, 465 468 Demetris Leadership Center case study, 472 480 QuickSort, 1125 1129 selection sort, 469 472 for STL vector, 480 485 source code, 11, 12 source le, 11 specialization, inheritance and, 869 870 specialized templates, 982 speci cation le, class, 729 spreadsheets, 265, 651 sqrt library function, 127 128 srand library function, 129 stack (STL type), 1071 1072, 1083
stacks, 1043 1072 applications of, 1044 array-based, 1044 1051 cafeteria plates, 1043 1044 described, 1043 1044 dynamic, 1044, 1060 1070 isEmpty operation, 1045 isFull operation, 1045 LIFO, 1043 linked list-based, 1060 1065 for math, 1051 1054 operations, 1044 1045, 1051 1054 pop, 1044 1045 push, 1044 static, 1044 1051, 1054 1060 STL stack container, 1071 1072 unwinding, 964 stale data, 724 standard C++, prestandard and, 74 76 Standard Template Library (STL), 427, 983 996 abstract data types, 983 984 algorithms, 984 986, 990 996 associative containers, 983, 984 binary_search algorithm, 984, 990 991 count algorithm, 985, 992 993 deque, 983, 1093 1094 find algorithm, 985, 994 995 for_each algorithm, 985, 995 996 iterators, 983, 987 989 list, 983, 1035 1036 map, 984 max_element algorithm, 985, 992 994 min_element algorithm, 985, 992 994 multimap, 984 multiset, 984 queue, 1094 1095 random_shuffle algorithm, 986, 990 991 sequence containers, 983 set, 984 sort algorithm, 986, 990 991 stack, 1071 1072 vector, 427 438, 480 485, 983, 986 987 starting size, vector, 428 state, object, 721 statements, 15 16 static binding, 909 static key word, 801 static local variables, 344 346 static member functions, 804 807 static member variables, 800 804
static queues, 1073, 1076 1084 static stacks, 1044 1051, 1054 1060 static_cast, 103 106 STL, see Standard Template Library storage, secondary, 5 6 strcat library function, 553 556, 561 strcmp library function, 558 562 strcpy library function, 554 556, 562 stream insertion operator, 31 32, 270, 579 stream manipulator, 33 stream object, 31 string class, 574 585, 711 append member function, 582 assign member function, 582 at member function, 582 begin member function, 582 capacity member function, 582 clear member function, 582 compare member function, 583 comparing and sorting, 576 578 constructors, 754 copy member function, 583 data member function, 583 de ning string objects, 574 575, 578 580 described, 51 52 empty member function, 583 end member function, 583 erase member function, 583 find member function, 583 Home Software Company case study, 584 585 input, reading into a string object, 576 insert member function, 583 length member function, 580 581, 583 member functions, 580 583 operators, 579 replace member function, 583 resize member function, 583 size member function, 583 substr member function, 583 swap member function, 583 using, 51 52 string constant, 29 string header le, 51, 574 string literals, 29, 39 40, 49 51, 549 550 string objects, 51 and characters, 120 126 comparing, 196 198 de ning, 574 575, 578 580 member functions and operators, 126 reading input into, 576
Index
strings, see also C-strings functions for handling, 568 573 numeric conversion functions, 563 568 sorting, 560 561 strlen library function, 552 553, 561 strncat library function, 562 strncpy library function, 562 strstr library function, 556 558, 562 struct, 595, see also structures structure pointer operator (->), 618 622 structure variables, 596 597, 602 structures, 593 637 and abstract data types, 593 595 accessing structure members, 598 602 arrays of, 605 608 combining data into, 595 598 containing pointers, 683 and enumerated data types, 627 637 as function arguments, 612 615 initializing, 602 604 nested, 608 611 pointers as members of, 621 622 pointers to, 618 621 records, creating with, 679 683 returning, from a function, 615 617 self-referential, 1005 and unions, 623 627 stubs, 363 style, programming, see programming style subscript, of array element, 379, 380 substr member function, string class, 583 subtraction operator (-), 61, 92 94 sums, of array values, 397 398, 421 423 swap member function list, 1036 string class, 583 vector, 438 switch statement, 202 209 break, 204, 205 case, 203 204 default, 203 204 fallthrough capability, 205 207 with menus, 207 209 syntax, 14 syntax errors, 11 system software, 6 7
T
U
tags, of structures, 596 tan library function, 127 tellg member function, le stream objects, 688 690 tellp member function, le stream objects, 688 690 template pre x, 967, 973 974 templates binary trees, 1157 1163 class, 973 982 de ning, 972 973 dynamic queue, 1089 1092 dynamic stack, 1065 1070 function, 966 973 linked list, 1022 1027 pre xes, 967, 973 974 specialized, 982 static queue, 1081 1084 static stack, 1054 1060 type parameter, 967 ternary operator, 60, 199 test expression (for loop), 248 text editor, 11 12 text les described, 267 numeric data from, 277 278 this pointer, 823 824 throw key word, 948, 964 throw point, 948 throwing an exception, 519, 948 time library function, 129 tolower library function, 545 top-down design, 20 top member function, stack, 1083 toupper library function, 545 Towers of Hanoi, 1122 1125 trailing else, 177 179 trailing zeroes, displaying, 118 traversing binary tree, 1144 1147 linked list, 1012 1013 true values, 150, 152 153, 160 161 truncation, 55 truth, 152 153, 160 161 try block, 949 try/catch construct, 949 951 try key word, 949 two-dimensional arrays, 416 423 initializing, 418 419 passing, to functions, 419 421 summing elements of, 421 423 type cast expression, 103 type casting, 103 106 type coercion, 101 type parameters, 967, 974
UML, see Uni ed Modeling Language unary operator, 60 under ow, 102 103 Uni ed Modeling Language (UML), 774 777, 852, see also Appendix E on the book s companion Web site access speci cation, showing, 775 776 aggregation, showing, 852 853 class diagram, 774 777 constructors, showing, 777 data type notation, 776 destructors, showing, 777 parameter notation, 776 unions, 623 627 anonymous, 625 627 structures vs., 623 unique member function, list, 1036 United Cause case study, 529 534 unsetf member function, cout, see Appendix L on the book s companion Web site unsigned int, 43 44 unsigned long, 43 44 unsigned short, 43 44 unwinding the stack, 964 update expression (for loop), 248, 252 256 uppercase conversion, character, 545 547 USB drives, 6 user-controlled loops, 244, 252 253 user-speci ed lenames, 283 284 using namespace statement, 28, 74, see also Appendix F on the book s companion Web site utility programs, 7
V validation, input, 193 194, 239 241 value, passing by, 318 319, 633 value-returning functions, 326 336 variable declaration, 16 variable de nitions, 17, 37 38, 59, 211 213 variables, 16 17, 37 39 accumulator, 257 259 counter, 241 242 ag, 181 182 global, 338 340, 343 initialization, 59 instance, 799 801 legal names, 42 lifetime of, 338 local, 327, 336 338, 343 loop control, 235
1213
1214
Index
variables (continued) names, 16, 41 42 over ow and under ow, 102 103 pointer, see pointers reference, 350 354, 494 495, 509 with same names, 213 214, 343 scope, 59 60, 211 213 static member, 800 804 structure, 596 597, 602 vector, 427 438, 480 485, 983, 986 987 [ ] operator, 986 at member function, 437, 989 back member function, 989 begin member function, 989 capacity member function, 437, 989 clear member function, 434 435, 437, 990 compared to linked list, 1003 1004 de ning, 427 428 empty member function, 435 437, 990
end member function, 990 erase member function, 990 front member function, 990 insert member function, 990 pop_back member function, 433 434, 437, 986 push_back member function, 430 432, 438, 986 removing elements from, 433 434 resize member function, 438, 990 reverse member function, 438, 990 searching and sorting, 480 485 size member function, 432 433, 986 storing and retrieving values in, 428 432 swap member function, 438 virtual destructors, 918 921 virtual functions and polymorphism, 909 913 pure, 921 925 Visual Basic, 10
void functions, 303 304 volatile memory, RAM as, 5
W Web browsers, 265 while loops, 232 241, 262 input validation with, 239 241 logic of, 233 235 as pretest loop, 235 programming style, 237 238 whitespace characters, 120 121 whole-part relationship, 851 width member function, cout and cin, see Appendix L on the book s companion Web site word processors, 265, 651 write member function, le stream objects, 675 writing data, to le, 265
Z zero(es) division by, 167 trailing, 118