LOCATION OF VIDEO NOTES IN THE TEXT Chapter 1
Introduction to Flowcharting, p. 19 Designing a Program with Pseudocode, p. 19 Designing the Account Balance Program, p. 25 Predicting the Result of Problem 33, p. 25
Chapter 2
Using cout, p. 33 Variable Definitions, p. 39 Assignment Statements and Simple Math Expressions, p. 61 Solving the Restaurant Bill problem, p. 77
Chapter 3
Reading Input with cin, p. 83 Formatting Numbers with setprecision, p. 119 Writing Data to a File, p. 144 Reading Data from a File, p. 145 Solving the Stadium Seating Problem, p. 156
Chapter 4
The if Statement, p. 168 The if/else Statement, p. 181 The if/else if Statement, p. 191 Solving the Time Calculator Problem, p. 239
Chapter 5
The while Loop, p. 254 The for Loop, p. 270 Solving the Calories Burned Problem, p. 299
Chapter 6
Functions and Arguments, p. 319 Value-Returning Functions, p. 332 Solving the Markup Problem, p. 375
Chapter 7
Accessing Array Elements with a Loop, p. 392 Passing an Array to a Function, p. 415 Solving the Chips and Salsa Problem, p. 457
Chapter 8
The Binary Search, p. 470 The Selection Sort, p. 485 Solving the Charge Account Validation Modification Problem, p. 503
Chapter 9
Dynamically Allocating an Array, p. 535 Solving the getString Function Problem, p. 554
Chapter 10
Writing a C-String-Handling Function, p. 582 Using the string Class, p. 588 Solving the Backward String Problem, p. 602 (continued on next page)
LOCATION OF VIDEO NOTES IN THE TEXT
(continued)
Chapter 11
Creating a Structure, p. 611 Passing a Structure to a Function, p. 630 Solving the Weather Statistics Problem, p. 664
Chapter 12
Passing File Stream Objects to Functions, p. 683 Working with Multiple Files, p. 695 Solving the File Encryption Filter Problem, p. 725
Chapter 13
Writing a Class, p. 736 Defining an Instance of a Class, p. 741 Solving the Employee Class Problem, p. 816
Chapter 14
Operator Overloading, p. 843 Class Aggregation, p. 872 Solving the NumDays Problem, p. 888
Chapter 15
Redefining a Base Class Function in a Derived Class, p. 917 Polymorphism, p. 927 Solving the Employee and ProductionWorker Classes Problem, p. 960
Chapter 16
Throwing an Exception, p. 972 Handling an Exception, p. 973 Writing a Function Template, p. 991 Storing Objects in a vector , p. 1011 Solving the Exception Project Problem, p. 1025
Chapter 17
Appending a Node to a Linked List, p. 1030 Inserting a Node in a Linked List, p. 1037 Deleting a Node from a Linked List, p. 1042 Solving the Member Insertion by Position Problem, p. 1064
Chapter 18
Storing Objects in an STL stack, p. 1083 Storing Objects in an STL queue, p. 1098 Solving the File Compare Problem, p. 1104
Chapter 19
Reducing a Problem with Recursion, p. 1112 Solving the Recursive Multiplication Problem, p. 1141
Chapter 20
Inserting a Node in a Binary Tree, p. 1150 Deleting a Node from a Binary Tree, p. 1156 Solving the Node Counter Problem, p. 1167
From Control Structures through Objects 6th Edition
Tony Gaddis
Executive Editor Editorial Assistant Senior Production Supervisor Text Designer Cover Designer Cover Image Media Producer Senior Media Buyer Marketing Manager Senior Manufacturing Buyer Production Services
Michael Hirsch Stephanie Sellinger Marilyn Lloyd Joyce Cosentino Wells Beth Paquin iStockphoto Bethany Tidd Ginny Michaud Christopher Kelly Carol Melville Aptara, Inc.
Access the latest information about Addison-Wesley titles from our World Wide Web site: http:www.aw.com/computing Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial caps or all caps. The programs and applications presented in this book have been included for their instructional value. They have been tested with care but are not guaranteed for any particular purpose. The publisher does not offer any warranty or representation, nor does it accept any liabilities with respect to the programs or applications. Library of Congress Cataloging-in-Publication Data Gaddis, Tony. Starting out with C++ : from control structures through objects / Tony Gaddis. — 6th ed. p. cm. Includes index. ISBN-13: 978-0-321-54588-6 ISBN-10: 0-321-54588-5 1. C++ (Computer program language) I. Title. QA76.73.C153G33 2008 005.13'3—dc22
2008008001 Copyright © 2009 Pearson Education, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. For information on obtaining permission for use of material in this work, please submit a written request to Pearson Education, Inc., Rights and Contracts Department, 501 Boylston Street, Suite 900, Boston, MA 02116, fax your request to 617-671-3447, or e-mail at http://www.pearsoned.com/legal/permissions.htm. ISBN 13: 978-0-321-54588-6 ISBN 10: 0-321-54588-5 1 2 3 4 5 6 7 8 9 10—QWT—11 10 09 08
Contents at a Glance
CHAPTER 1 CHAPTER 2 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
Preface xiii Introduction to Computers and Programming 1 Introduction to C++ 29 Expressions and Interactivity 83 Making Decisions 163 Looping 249 Functions 307 Arrays 387 Searching and Sorting Arrays 467 Pointers 507 Characters, Strings, and the string Class 559 Structured Data 609 Advanced File Operations 673 Introduction to Classes 729 More About Classes 825 Inheritance, Polymorphism, and Virtual Functions 895 Exceptions, Templates, and the Standard Template Library (STL) Linked Lists 1027 Stacks and Queues 1067 Recursion 1107 Binary Trees 1145 Appendix A: Getting Started with Alice 1171 Appendix B: The ASCII Character Set 1199 Appendix C: Operator Precedence and Associativity Index 1205
971
1203
v
vi
Contents at a Glance
Student CD
The following appendices are on the accompanying Student CD. 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++ 2008 Express Edition Appendix N: Answers to Checkpoints Appendix O: Answers to Odd Numbered Review Questions
Contents Table of Location of Video Notes Preface
xiii
CHAPTER 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7
Introduction to Computers and Programming Why Program? 1 Computer Systems: Hardware and Software 2 Programs and Programming Languages 6 What Is a Program Made of? 12 Input, Processing, and Output 16 The Programming Process 17 Procedural and Object-Oriented Programming 21
1
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
Introduction to C++ 29 The Parts of a C++ Program 29 The cout Object 33 The #include Directive 38 Variables and Literals 39 Identifiers 43 Integer Data Types 44 The char Data Type 49 Floating-Point Data Types 54 The bool Data Type 57 Determining the Size of a Data Type 58 Variable Assignments and Initialization 59 Scope 60 Arithmetic Operators 61 Comments 67 Focus on Software Engineering: Programming Style 69 If You Plan to Continue in Computer Science: Standard and Prestandard C++
CHAPTER 3 3.1 3.2 3.3
Expressions and Interactivity 83 The cin Object 83 Mathematical Expressions 91 When You Mix Apples and Oranges: Type Conversion
100
71
vii
viii
Contents
3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14
Overflow and Underflow 102 Type Casting 104 Named Constants 107 Multiple Assignment and Combined Assignment 112 Formatting Output 116 Formatted Input 125 Focus on Object-Oriented Programming: More About Member Functions More Mathematical Library Functions 131 Focus on Debugging: Hand Tracing a Program 135 Focus on Problem Solving: A Case Study 137 Introduction to File Input and Output 140
CHAPTER 4 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15 4.16
Making Decisions 163 Relational Operators 163 The if Statement 168 Flags 176 Expanding the if Statement 177 The if/else Statement 181 Nested if Statements 184 The if/else if Statement 191 Menus 195 Logical Operators 199 Checking Numeric Ranges with Logical Operators 206 Focus on Software Engineering: Validating User Input 207 More About Variable Definitions and Scope 209 Comparing Strings 213 The Conditional Operator 218 The switch Statement 222 Testing for File Open Errors 231
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 5.13
Looping 249 The Increment and Decrement Operators 249 Introduction to Loops: The while Loop 254 Using the while Loop for Input Validation 261 Counters 263 The do-while Loop 265 The for Loop 270 Keeping a Running Total 280 Sentinels 283 Using a Loop to Read Data from a File 284 Focus on Software Engineering: Deciding Which Loop to Use Nested Loops 287 Breaking Out of a Loop 290 The continue Statement 292
CHAPTER 6 6.1 6.2 6.3
Functions 307 Focus on Software Engineering: Modular Programming Defining and Calling Functions 309 Function Prototypes 317
307
287
130
Contents
6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 6.15 6.16
Sending Data into a Function 319 Passing Data by Value 324 Focus on Software Engineering: Using Functions in a Menu-Driven Program The return Statement 330 Returning a Value from a Function 332 Returning a Boolean Value 340 Local and Global Variables 342 Static Local Variables 350 Default Arguments 353 Using Reference Variables as Parameters 356 Overloading Functions 362 The exit() Function 366 Stubs and Drivers 369
CHAPTER 7 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 7.11 7.12
Arrays 387 Arrays Hold Multiple Values 387 Accessing Array Elements 389 No Bounds Checking in C++ 396 Array Initialization 399 Processing Array Contents 404 Focus on Software Engineering: Using Parallel Arrays 412 Arrays as Function Arguments 415 Two-Dimensional Arrays 426 Arrays of Strings 433 Arrays with Three or More Dimensions 435 Focus on Problem Solving and Program Design: A Case Study 437 If You Plan to Continue in Computer Science: Introduction to the STL vector 439
CHAPTER 8 8.1 8.2
Searching and Sorting Arrays 467 Focus on Software Engineering: Introduction to Search Algorithms 467 Focus on Problem Solving and Program Design: A Case Study 474 Focus on Software Engineering: Introduction to Sorting Algorithms 480 Focus on Problem Solving and Program Design: A Case Study 488 If You Plan to Continue in Computer Science: Sorting and Searching vectors 496
8.3 8.4 8.5
CHAPTER 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10
Pointers 507 Getting the Address of a Variable 507 Pointer Variables 509 The Relationship Between Arrays and Pointers 516 Pointer Arithmetic 520 Initializing Pointers 522 Comparing Pointers 523 Pointers as Function Parameters 525 Focus on Software Engineering: Dynamic Memory Allocation 534 Focus on Software Engineering: Returning Pointers from Functions 538 Focus on Problem Solving and Program Design: A Case Study 545
ix
326
x
Contents
CHAPTER 10 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 CHAPTER 11 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 11.10 11.11 11.12
Characters, Strings, and the string Class 559 Character Testing 559 Character Case Conversion 563 Review of the Internal Storage of C-Strings 566 Library Functions for Working with C-Strings 569 String/Numeric Conversion Functions 577 Focus on Software Engineering: Writing Your Own C-String-Handling Functions 582 The C++ string Class 588 Focus on Problem Solving and Program Design: A Case Study
Structured Data 609 Abstract Data Types 609 Focus on Software Engineering: Combining Data into Structures 611 Accessing Structure Members 614 Initializing a Structure 619 Arrays of Structures 623 Focus on Software Engineering: Nested Structures 626 Structures as Function Arguments 630 Returning a Structure from a Function 633 Pointers to Structures 636 Focus on Software Engineering: When to Use ., When to Use ->, and When to Use * 639 Unions 641 Enumerated Data Types 645
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 673 File Operations 673 File Output Formatting 680 Passing File Stream Objects to Functions 683 More Detailed Error Testing 685 Member Functions for Reading and Writing Files 688 Focus on Software Engineering: Working with Multiple Files Binary Files 696 Creating Records with Structures 702 Random-Access Files 706 Opening a File for Both Input and Output 714
CHAPTER 13 13.1 13.2 13.3 13.4 13.5
Introduction to Classes 729 Procedural and Object-Oriented Programming 729 Introduction to Classes 736 Defining an Instance of a Class 741 Why Have Private Members? 752 Focus on Software Engineering: Separating Class Specification from Implementation 753 Inline Member Functions 759 Constructors 762 Passing Arguments to Constructors 766 Destructors 774
13.6 13.7 13.8 13.9
598
695
Contents
13.10 13.11 13.12 13.13 13.14 13.15 13.16
Overloading Constructors 778 Private Member Functions 782 Arrays of Objects 784 Focus on Problem Solving and Program Design: An OOP Case Study 788 Focus on Object-Oriented Programming: Creating an Abstract Array Data Type 795 Focus on Object-Oriented Design: The Unified Modeling Language (UML) 799 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 802
CHAPTER 14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8
More About Classes 825 Instance and Static Members 825 Friends of Classes 833 Memberwise Assignment 838 Copy Constructors 839 Operator Overloading 843 Object Conversion 870 Aggregation 872 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 895 What Is Inheritance? 895 Protected Members and Class Access 904 Constructors and Destructors in Base and Derived Classes 910 Redefining Base Class Functions 917 Class Hierarchies 921 Polymorphism and Virtual Member Functions 927 Abstract Base Classes and Pure Virtual Functions 942 Multiple Inheritance 949
CHAPTER 16 16.1 16.2 16.3 16.4 16.5
Exceptions, Templates, and the Standard Template Library (STL) 971 Exceptions 971 Function Templates 990 Focus on Software Engineering: Where to Start When Defining Templates 996 Class Templates 997 Introduction to the Standard Template Library (STL) 1007
CHAPTER 17 17.1 17.2 17.3 17.4 17.5
Linked Lists 1027 Introduction to the Linked List ADT Linked List Operations 1029 A Linked List Template 1046 Variations of the Linked List 1058 The STL list Container 1059
CHAPTER 18 18.1 18.2 18.3 18.4
Stacks and Queues 1067 Introduction to the Stack ADT 1067 Dynamic Stacks 1078 The STL stack Container 1083 Introduction to the Queue ADT 1085
1027
878
xi
xii
Contents
18.5 18.6 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
Dynamic Queues 1093 The STL deque and queue Containers
1097
Recursion 1107 Introduction to Recursion 1107 Solving Problems with Recursion 1112 Focus on Problem Solving and Program Design: The Recursive gcd Function 1119 Focus on Problem Solving and Program Design: Solving Recursively Defined Problems 1120 Focus on Problem Solving and Program Design: Recursive Linked List Operations 1122 Focus on Problem Solving and Program Design: A Recursive Binary Search Function 1125 The Towers of Hanoi 1128 Focus on Problem Solving and Program Design: The QuickSort Algorithm Exhaustive Algorithms 1136 Focus on Software Engineering: Recursion vs. Iteration 1138 Binary Trees 1145 Definition and Applications of Binary Trees 1145 Binary Search Tree Operations 1148 Template Considerations for Binary Search Trees 1165 Appendix A: Getting Started with Alice 1171 Appendix B: The ASCII Character Set 1199 Appendix C: Operator Precedence and Associativity Index 1205
Student CD
1131
1203
The following appendices are on the accompanying Student CD. 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++ 2008 Express Edition Appendix N: Answers to Checkpoints Appendix O: Answers to Odd Numbered Review Questions
Preface Welcome to Starting Out with C++: From Control Structures through Objects, 6th edition. This book is intended for use in a two-semester C++ programming sequence, or an accelerated one-semester course. Students new to programming, as well as those with prior course work in other languages, will find this text beneficial. The fundamentals of programming are covered for the novice, while the details, pitfalls, and nuances of the C++ language are explored in-depth for both the beginner and more experienced student. The book is written with clear, easy-to-understand language and it covers all the necessary topics for an introductory programming course. This text is rich in example programs that are concise, practical, and real-world oriented, ensuring that the student not only learns how to implement the features and constructs of C++, but why and when to use them.
Changes in the Sixth 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: •
Improved Organization in Chapter 4 The section covering the if/else if statement has been simplified, and now appears immediately following the section on nested if statements. These sections have been rewritten to highlight the similarities between an if/else if statement and a nested if statement.
•
New In the Spotlight Sections Many of the chapters have new sections titled In the Spotlight. Each of these provides a programming problem and a detailed, step-by-step analysis showing the student how to solve it.
•
Online Video Notes An extensive series of online videos have been developed to accompany this text. Throughout the book, video note icons alert the student to videos covering specific topics. Additionally, one Programming Challenge at the end of each chapter now has an accompanying video note explaining how to develop the problem’s solution. The videos are available at http://www.aw.com/gaddis/videonotes.
xiii
xiv
Preface
•
Additional Programming Problems Additional Programming Challenge problems have been added to most chapters. Several of these are simple games that will challenge and motivate students.
•
New Appendix: Getting Started with Alice This new appendix gives a quick introduction to Alice. Alice is free software that can be used to teach fundamental programming concepts using 3D graphics.
Organization of the Text This text teaches C++ in a step-by-step fashion. Each chapter covers a major set of topics and builds knowledge as the student progresses through the book. Although the chapters can be easily taught in their existing sequence, some flexibility is provided. The diagram shown in Figure P-1 suggests possible sequences of instruction. Chapter 1 covers fundamental hardware, software, and programming concepts. You may choose to skip this chapter if the class 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 firm foundation in structured, procedural programming before delving fully into object-oriented programming and advanced data structures.
Brief Overview of Each Chapter Chapter 1: Introduction to Computers and Programming This chapter provides an introduction to the field of computer science and covers the fundamentals of programming, problem solving, and software design. The components of programs, such as key words, variables, operators, and punctuation are covered. The tools of the trade, such as pseudocode, flow charts, and hierarchy charts are also presented.
Chapter 2: Introduction to C++ This chapter gets the student started in C++ by introducing data types, identifiers, variable declarations, constants, comments, program output, simple arithmetic operations, and 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 C-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 using sequential files, on simple output formatting, on data type conversion and type casting, and on using library functions that work with numbers.
Chapter 4: Making Decisions Here the student learns about relational operators, relational expressions and how to control the flow of a program with the if, if/else, and if/else if statements. The conditional operator and the switch statement are also covered. Crucial applications of these constructs are covered, such as menu-driven programs and the validation of input.
Chapter 5: Looping 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. A section on file I/O discusses how to use a loop to read from a file until the end of the file is encountered.
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 find the sum, average, highest and lowest values in an array and how to sum the rows, columns, and all elements of a two-dimensional array. Programming techniques using parallel arrays are also demonstrated and the student is shown how to use a data file as an input source to populate an array. STL vectors are introduced and compared to arrays.
Chapter 8: 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 the Standard string Class This chapter focuses on library functions that manipulate or test characters or strings. A review of the internal storage of C-strings is given. An extensive discussion of the standard string class is also presented.
Chapter 11: Structured Data The student is introduced to abstract data types and taught how to create them using structures, unions, and enumerated data types. Discussions and examples include using pointers to structures, passing structures to functions, and returning structures from functions.
Chapter 12: Advanced File Operations This chapter covers sequential access, random access, text, and binary files. The various modes for opening files are discussed, as well as the many methods for reading and writing file contents. Advanced output formatting is also covered.
Chapter 13: Introduction to Classes The student now shifts focus to the object-oriented paradigm. This chapter covers the fundamental concepts of classes. Member variables and functions are discussed. The student learns about private and public access specifications, and reasons to use each. The topics of constructors, overloaded constructors, and destructors are also presented. The chapter presents a section modeling classes with UML, and how to find the classes in a particular problem.
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 defined, 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 finding factorials, finding a greatest common denominator (GCD), performing a binary search, and sorting (QuickSort). The classic Towers of Hanoi example is also presented. For students who need more challenge, there is a section on exhaustive algorithms.
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 on the accompanying Student CD
Appendix D: Introduction to Flowcharting A brief introduction to flowcharting. 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 Unified Modeling Language to design classes. Notation for showing access specification, 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 define 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 MS-DOS prompt console.
Appendix I: Header File and Library Function Reference This appendix provides a reference for the C++ library functions and header files 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 files. Function header files, class specification files, and class implementation files 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++ 2008 Express Edition A tutorial on how to start a project in Microsoft Visual C++ 2008 Express Edition, compile a program, save source files, 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: Answers to Odd-Numbered Review Questions Another tool that students can use to gauge their progress.
Features of the Text Concept Statements
Each major section of the text starts with a concept statement. This statement summarizes the ideas of the section.
Example Programs
The text has over 300 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.
Video Notes
A series of online videos, developed specifically for this book, are available for viewing at http://www.aw.com/gaddis/ videonotes. Icons appear throughout the text alerting the student to videos about specific topics.
Checkpoints
Checkpoints are questions placed throughout each chapter as a self-test study aid. Answers for all Checkpoint questions are provided on the student CD so students can check how well they have learned a new topic.
Notes
Notes appear at appropriate places throughout the text. They are short explanations of interesting or often misunderstood points relevant to the topic at hand.
Warnings
Warnings are notes that caution the student about certain C++ features, programming techniques, or practices that can lead to malfunctioning programs or lost data.
Preface
Case Studies
Case studies that simulate real-world applications appear in many chapters throughout the text, with complete code provided for each one on the student CD. These case studies are designed to highlight the major topics of the chapter in which they appear.
Review Questions and Exercises
Each chapter presents a thorough and diverse set of review questions, such as fill-in-the-blank and short answer, that check the student’s mastery of the basic 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 are provided on the student CD.
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
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 fictitious 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 page of the book and the inside back cover.
xxi
xxii
Preface
Supplements Student CD This CD includes: •
Borland Turbo C++ Explorer Edition
•
Answers to all Checkpoint questions (Appendix N)
•
Answers to all odd-numbered Review Questions and Exercises (Appendix O)
•
Complete source code for every program included in the book
•
Additional case studies, complete with source code
•
A full set of appendices (including several tutorials) that accompany the book
If a CD did not come with your book or you can’t locate your CD, you can access most of these items at http://www.aw.com/cssupport/
Other CDs Upon Request Professors should contact their campus Addison-Wesley representative for the specific ISBN to order this book packaged with Microsoft Visual C++ 2008 Express Edition.
MyCodeMate—Your Own T.A. Just a Click Away Addison-Wesley’s MyCodeMate is a book-specific Web resource that provides tutorial help and evaluation of student programs. Example programs throughout the book and selected Programming Challenges from every chapter have been integrated into MyCodeMate. Using this tool, a student is able to write and compile programs from any computer with Internet access, and receive guidance and feedback on how to proceed and on how to address compiler error messages. Instructors can track each student’s progress on Programming Challenges from the text or can develop projects of their own. A complimentary subscription to MyCodeMate is offered when the access code is ordered in a package with a new copy of this text. Subscriptions can also be purchased online. For more information visit http:// www.mycodemate.com, or contact your campus Addison-Wesley representative.
Instructor Resources The following supplements are available to qualified instructors only: •
Answers to all Review Questions in the text
•
Solutions for all Programming Challenges in the text
•
PowerPoint presentation slides for every chapter
•
Computerized test bank
•
Answers to all Student Lab Manual questions
•
Solutions for all Student Lab Manual programs
Visit the Addison-Wesley Instructor Resource Center (http://www.aw.com/irc) or send an email to
[email protected] for information on how to access them.
Preface
Textbook Web site A Web site for the Starting Out with C++ series of books is located at the following URL: http://www.aw.com/gaddisbooks
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 fit your course: •
Starting Out with C++: From Control Structures through Objects (formerly called the “Standard Version”);
• •
Starting Out with C++: Early Objects (formerly called the “Alternate Version”); 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.
USE OF C-STRINGS Null-terminated C-strings are used throughout, with the C++ string class covered briefly.
USE OF string OBJECTS Standard library string class objects are used throughout, with C-strings covered briefly.
INTRODUCTION OF DATA STRUCTURES AND RECURSION Linked lists, stacks and queues, and binary trees are introduced in the final 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 final 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
Judy Etchison Southern Methodist University
Mary Astone Troy University
Dennis Fairclough Utah Valley State College
Ijaz A. Awan Savannah State University
Richard Flint North Central College
Robert Baird Salt Lake Community College
Ann Ford Florida State University
Don Biggerstaff Fayetteville Technical Community College
James Gifford University of Wisconsin, Stevens Point
Michael Bolton Northeastern Oklahoma State University
Leon Gleiberman Touro College
Bill Brown Pikes Peak Community College
Ranette Halverson, Ph.D. Midwestern State University
Charles Cadenhead Richland Community College
Carol Hannahs University of Kentucky
Randall Campbell Morningside College
Dennis Heckman Portland Community College
Wayne Caruolo Red Rocks Community College
Ric Heishman George Mason University
Cathi Chambley-Miller Aiken Technical College
Michael Hennessy University of Oregon
C.C. Chao Jacksonville State University
Ilga Higbee Black Hawk College
Joseph Chao Bowling Green State University
Patricia Hines Brookdale Community College
Preface
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
James McGuffee Austin Community College
William Slater Collin County Community College
Dean Mellas Cerritos College
Shep Smithline University of Minnesota
Lisa Milkowski Milwaukee School of Engineering
Caroline St. Claire North Central College
Marguerite Nedreberg Youngstown State University
Kirk Stephens Southwestern Community College
xxv
xxvi
Preface
Cherie Stevens South Florida Community College
Arisa K. Ude Richland College
Dale Suggs Campbell University
Peter van der Goes Rose State College
Mark Swanson Red Wing Technical College
Stewart Venit California State University, Los Angeles
Martha Tillman College of San Mateo
Judy Walters North Central College
Ralph Tomlinson Iowa State University
John H. Whipple Northampton Community College
David Topham Ohlone College
Aurelia Williams Norfolk State University
Robert Tureman Paul D. Camp Community College
Vida Winans Illinois Institute of Technology
First, I would like to thank my family for their many years of support, and my students at Haywood Community College for inspiring me to write student-friendly books. I owe a debt of gratitude to everyone at Addison-Wesley who is part of the editorial, production, and marketing team for this book. I am very fortunate to have Michael Hirsch as my editor, guiding me through all phases of development and production. I am also fortunate to work with Chris Kelly, Marilyn Lloyd, Stephanie Sellinger, Bethany Tidd, Joyce Wells, and Shelley Creager. This book would not be possible without your tireless work. You are all great people to work with!
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®, and Python, all published by Addison-Wesley.
xxvii
This page intentionally left blank
CHAPTER
1
Introduction to Computers and Programming
TOPICS 1.1 1.2 1.3
1.1
Why Program? Computer Systems: Hardware and Software Programs and Programming Languages
1.4 1.5 1.6 1.7
What Is a Program Made of? Input, Processing, and Output The Programming Process Procedural and Object-Oriented Programming
Why Program? CONCEPT: Computers can do many different jobs because they are programmable. Every profession has tools that make its job easier to do. Carpenters use hammers, saws, and measuring tapes. Mechanics use wrenches, screwdrivers, and ratchets. Electronics technicians use probes, scopes, and meters. Some tools are unique and can be categorized as belonging to a single profession. For example, surgeons have certain tools that are designed specifically for surgical operations. Those tools probably aren’t used by anyone other than surgeons. There are some tools, however, that are used in several professions. Screwdrivers, for instance, are used by mechanics, carpenters, and many others. The computer is a tool that is used by so many professions that it cannot be easily categorized. It can perform so many different jobs that it is perhaps the most versatile tool ever made. To the accountant, computers balance books, analyze profits and losses, and prepare tax reports. To the factory worker, computers control manufacturing machines and track production. To the mechanic, computers analyze the various systems in an automobile and pinpoint hard-to-find problems.
1
2
Chapter 1
Introduction to Computers and Programming
What makes the computer so useful? Quite simply, the computer can do such a wide variety of tasks because it can be programmed. It is a machine specifically designed to follow instructions. Because of the computer’s programmability, it doesn’t belong to any single profession. Computers are designed to do whatever task their programs, or software, tell them to do. Computer programmers do a very important job. They create software that transforms computers into the specialized tools of many trades. Without programmers, the users of computers would have no software, and without software, computers would not be able to do anything. 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 scientific, or engineering, side to programming. Because programs rarely work right the first time they are written, a lot of testing, correction, and redesigning is required. This demands patience and persistence from the programmer. Writing software demands discipline as well. Programmers must learn special languages like C++ because computers do not understand English or other human languages. Languages such as C++ have strict rules that must be carefully followed. Both the artistic and scientific nature of programming make writing computer software like designing a car: Both cars and programs should be functional, efficient, powerful, easy to use, and pleasing to look at.
1.2
Computer Systems: Hardware and Software CONCEPT: All computer systems consist of similar hardware devices and software components. This section provides an overview of standard computer hardware and software organization.
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
1.2 Computer Systems: Hardware and Software
The organization of a computer system is depicted in Figure 1-1. Figure 1-1
Central Processing Unit
Output Devices
Input Devices
Main Memory (RAM) Secondary Storage Devices
The CPU At the heart of a computer is its central processing unit, or CPU. 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-2. Figure 1-2 Central Processing Unit Arithmetic and Logic Unit Instruction (Input)
Result (Output) Control Unit
3
4
Chapter 1
Introduction to Computers and Programming
A program is a sequence of instructions stored in the computer’s memory. When a computer is running a program, the CPU is engaged in a process known formally as the fetch/ decode/execute cycle. The steps in the fetch/decode/execute cycle are as follows: Fetch
The CPU’s control unit fetches, from main memory, the next instruction in the sequence of program instructions.
Decode
The instruction is encoded in the form of a number. The control unit decodes the instruction and generates an electronic signal.
Execute
The signal is routed to the appropriate component of the computer (such as the ALU, a disk drive, or some other device). The signal causes the component to perform an operation.
These steps are repeated as long as there are instructions to perform.
Main Memory Commonly known as random-access memory, or RAM, the computer’s main memory is a device that holds information. Specifically, RAM holds the sequences of instructions in the programs that are running and the data those programs are using. Memory is divided into sections, or cells, that each hold an equal amount of data. Each cell is made of eight “switches” that may be either on or off. A switch that is in the on position usually represents the number 1, while a switch in the off position usually represents the number 0. The computer stores data by setting the switches in a memory cell to a pattern that represents a character of information. Each of these switches is known as a bit, which stands for binary digit. Each cell, which is a collection of eight bits, is known as a byte. Each byte is assigned a unique number known as an address. The addresses are ordered from lowest to highest. A byte is identified by its address in much the same way a post office box is identified by an address. Figure 1-3 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-3 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
RAM is usually a volatile type of memory, used only for temporary storage. When the computer is turned off, the contents of RAM are erased.
Secondary Storage Secondary storage is a type of memory that can hold data for long periods of time—even when there is no power to the computer. Frequently used programs are stored in secondary memory and loaded into main memory as needed. Important information, such as word processing documents, payroll data, and inventory figures, is saved to secondary storage as well.
1.2 Computer Systems: Hardware and Software
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 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 floppy disk drives were popular. A floppy disk drive records data onto a small floppy disk, which can be removed from the drive. The use of floppy 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 flash memory to store data, are inexpensive, reliable, and small enough to be carried in your pocket. Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are also popular for data storage. Data is not recorded magnetically on an optical disc, but 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 As previously mentioned, software refers to the programs that run on a computer. There are two general categories of software: operating systems and application software. An operating system is a set of programs that manages the computer’s hardware devices and controls their processes. Operating systems fall into one of the following categories. Single tasking
A single tasking operating system is capable of running only one program at a time. The computer devotes all its hardware resources and CPU time to each program as it executes. MS-DOS is an example of a single tasking operating system.
5
6
Chapter 1
Introduction to Computers and Programming
Multitasking
A multitasking operating system is capable of running multiple programs at once. Through a technique called time sharing, the system divides the allocation of hardware resources and the attention of the CPU among all the executing programs. UNIX, Windows XP, and Windows Vista are multitasking operating systems.
In addition, operating systems fall into one of the following categories, which describe the number of users they can accommodate. Single user
This type of system allows only one user to operate the computer at a time. MS-DOS and older versions of Windows are single user operating systems.
Multiuser
Multiuser systems allow several users to run programs and operate the computer at once. Most variations of the UNIX operating system are multiuser systems.
Application software refers to programs that make the computer useful to the user. These programs solve specific problems or perform general operations that satisfy the needs of the user. Word processing, spreadsheet, and database programs are all examples of application software.
Checkpoint
1.3
1.1
Why is the computer used by so many different people, in so many different professions?
1.2
List the five major hardware components of a computer system.
1.3
Internally, the CPU consists of what two units?
1.4
Describe the steps in the fetch/decode/execute cycle.
1.5
What is a memory address? What is its purpose?
1.6
Explain why computers have both main memory and secondary storage.
1.7
What are the two general categories of software?
1.8
What is the difference between a single tasking system and a multitasking system?
1.9
What is the difference between a single user system and a multiuser system?
Programs and Programming Languages CONCEPT: A program is a set of instructions a computer follows in order to perform a task. A programming language is a special language used to write computer programs.
What Is a Program? Computers are designed to follow instructions. A computer program is a set of instructions that tells the computer how to solve a problem or perform a task. For example, suppose we want the computer to calculate someone’s gross pay. Here is a list of things the computer should do:
1.3 Programs and Programming Languages
1. Display a message on the screen asking “How many hours did you work?” 2. Wait for the user to enter the number of hours worked. Once the user enters a number, store it in memory. 3. Display a message on the screen asking “How much do you get paid per hour?” 4. Wait for the user to enter an hourly pay rate. Once the user enters a number, store it in memory. 5. Multiply the number of hours by the amount paid per hour, and store the result in memory. 6. Display a message on the screen that tells the amount of money earned. The message must include the result of the calculation performed in Step 5. Collectively, these instructions are called an algorithm. An algorithm is a set of welldefined steps for performing a task or solving a problem. Notice these steps are 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 difficult. 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 files, and then use special software to convert their programs to machine language. Program 1-1 shows how the pay-calculating algorithm might be written in C++. The “Program Output with Example Input” shows what the program will display on the screen when it is running. In the example, the user enters 10 for the number of hours worked and 15 for the hourly pay rate. The program displays the earnings, which are $150. NOTE: The line numbers that are shown in Program 1-1 are not part of the program. This book shows line numbers in all program listings to help point out specific parts of the program.
7
8
Chapter 1
Introduction to Computers and Programming
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; store2 -= sold; // Adjust store 2's inventory. // Get the number of widgets sold at store 3. cout > sold; store3 -= sold; // Adjust store 3's inventory. // Display each store's current inventory. cout width; cout > height; (program continues)
139
140
Chapter 3
Program 3-28 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
Expressions and Interactivity
(continued)
// Calculate the crate's volume, the cost to produce it, // the charge to the customer, and the profit. volume = length * width * height; cost = volume * 0.23; charge = volume * 0.5; profit = charge - cost; // Display the calculated data. cout 95) cout 40); cout = 35000 || years > 5)) { cout 2. It is asking “is x not greater than 2?” The second expression, however, applies the ! operator to x only. It is asking “is the logical negation of x greater than 2?” Suppose x is set to 5. Since 5 is nonzero, it would be considered true, so the ! operator would reverse it to false, which is 0. The > operator would then determine if 0 is greater than 2. To avoid a catastrophe like this, always use parentheses! The && and || operators rank lower in precedence than the relational operators, so precedence problems are less likely to occur. If you feel unsure, however, it doesn’t hurt to use parentheses anyway. (a > b) && (x < y) (x == y) || (b > a)
is the same as is the same as
a > b && x < y x == y || b > a
The logical operators have left-to-right associativity. In the following expression, a < b is evaluated before y == z. a < b || y == z
205
206
Chapter 4
Making Decisions
In the following expression, y == z is evaluated first, however, because the && operator has higher precedence than ||. a < b || y == z && m > j
The expression is equivalent to (a < b) || ((y == z) && (m > j))
4.10
Checking Numeric Ranges with Logical Operators CONCEPT: Logical operators are effective for determining whether a number is in or out of a range. When determining whether a number is inside a numeric range, it’s best to use the && operator. For example, the following if statement checks the value in x to determine whether it is in the range of 20 through 40: if (x >= 20 && x > choice; switch (choice) { case 'A': cout power; bigNum = num; while (count++ < power); bigNum *= num; cout using namespace std; int main () { string town; cout > town; cout , and When to Use * 11.11 Unions 11.12 Enumerated Data Types
Abstract Data Types CONCEPT: Abstract data types (ADTs) are data types created by the programmer. ADTs have their own range (or domain) of data and their own sets of operations that may be performed on them. The term abstract data type, or ADT, is very important in computer science and is especially significant in object-oriented programming. This chapter introduces you to the structure, which is one of C++’s mechanisms for creating abstract data types.
Abstraction An abstraction is a general model of something. It is a definition that includes only the general characteristics of an object. For example, the term “dog” is an abstraction. It defines a general type of animal. The term captures the essence of what all dogs are without specifying the detailed characteristics of any particular type of dog. According to Webster’s New Collegiate Dictionary, a dog is 609
610
Chapter 11
Structured Data
a highly variable carnivorous domesticated mammal (Canis familiaris) probably descended from the common wolf. In real life, however, there is no such thing as a mere “dog.” There are specific types of dogs, each with its own set of characteristics. There are poodles, cocker spaniels, Great Danes, rottweilers, and many other breeds. There are small dogs and large dogs. There are gentle dogs and ferocious dogs. They come in all shapes, sizes, and dispositions. A real-life dog is not abstract. It is concrete.
Data Types C++ has several primitive data types, or data types that are defined as a basic part of the language, as shown in Table 11-1. Table 11-1 bool
int
unsigned long int
char
long int
float
unsigned char
unsigned short int
double
short int
unsigned int
long double
A data type defines what values a variable may hold. Each data type listed in Table 11-1 has its own range of values, such as –32,768 to +32,767 for shorts, and so forth. Data types also define what values a variable may not hold. For example, integer variables may not be used to hold fractional numbers. In addition to defining a range or domain of values that a variable may hold, data types also define the operations that may be performed on a value. All of the data types listed in Table 11-1 allow the following mathematical and relational operators to be used with them: +
-
*
/
>
=
employee.payRate; // Calculate the employee's gross pay. employee.grossPay = employee.hours * employee.payRate; (program continues)
615
616
Chapter 11
Structured Data
Program 11-1 41 42 43 44 45 46 47 48 49 50
(continued)
// Display the employee data. cout manager.birthDate.day; cout > manager.birthDate.year; cin.ignore(); // Skip the remaining newline character // Get the manager's residence information cout , and . operators, and describes what each references. Table 11-3 Expression Description s->m s is a structure pointer and m is a member. This expression accesses the m member of the structure pointed to by s. *a.p a is a structure variable and p, a pointer, is a member. This expression dereferences the value pointed to by p. (*s).m s is a structure pointer and m is a member. The * operator dereferences s, causing the expression to access the m member of the structure pointed to by s. This expression is the same as s->m . *s->p s is a structure pointer and p, a pointer, is a member of the structure pointed to by s. This expression accesses the value pointed to by p. (The -> operator dereferences s and the * operator dereferences p.) *(*s).p s is a structure pointer and p, a pointer, is a member of the structure pointed to by s. This expression accesses the value pointed to by p. (*s) dereferences s and the outermost * operator dereferences p. The expression *s->p is equivalent.
Checkpoint Assume the following structure declaration exists for questions 11.11–11.15: struct Rectangle { int length; int width; };
11.11
Write a function that accepts a Rectangle structure as its argument and displays the structure’s contents on the screen.
11.12
Write a function that uses a Rectangle structure reference variable as its parameter and stores the user’s input in the structure’s members.
11.13
Write a function that returns a Rectangle structure. The function should store the user’s input in the members of the structure before returning it.
11.14
Write the definition of a pointer to a Rectangle structure.
11.15
Assume rptr is a pointer to a Rectangle structure. Which of the expressions, A, B, or C, is equivalent to the following expression: rptr->width
A) *rptr.width B) (*rptr).width C) rptr.(*width)
11.11 Unions
11.11
Unions CONCEPT: A union is like a structure, except all the members occupy the same memory area. A union, in almost all regards, is just like a structure. The difference is that all the members of a union use the same memory area, so only one member can be used at a time. A union might be used in an application where the program needs to work with two or more values (of different data types), but only needs to use one of the values at a time. Unions conserve memory by storing all their members in the same memory location. Unions are declared just like structures, except the key word union is used instead of struct. Here is an example: union PaySource { short hours; float sales; };
A union variable of the data type shown above can then be defined as PaySource employee1;
The PaySource union variable defined here has two members: hours (a short), and sales (a float). The entire variable will only take up as much memory as the largest member (in this case, a float). The way this variable is stored on a typical PC is illustrated in Figure 11-5. Figure 11-5 employee1: a PaySource union variable
First two bytes are used by hours, a short All four bytes are used by sales, a float
As shown in Figure 11-5, the union uses four bytes on a typical PC. It can store a short or a float, depending on which member is used. When a value is stored in the sales member, all four bytes are needed to hold the data. When a value is stored in the hours member, however, only the first two bytes are used. Obviously, both members can’t hold values at the same time. This union is demonstrated in Program 11-10.
641
642
Chapter 11
Structured Data
Program 11-10 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 48 49 50 51
// This program demonstrates a union. #include #include using namespace std; union PaySource { int hours; float sales; };
// Hours worked // Amount of sales
int main() { PaySource employee1; char payType; float payRate; float grossPay;
// // // //
Define a union variable To hold the pay type Hourly pay rate Gross pay
cout setWidth(10.0); rectPtr->setLength(15.0); // Delete the object from memory. delete rectPtr; rectPtr = 0;
Line 2 defines rectPtr as a Rectangle pointer. Line 5 uses the new operator to dynamically allocate a Rectangle object and assign its address to rectPtr. Lines 8 and 9 store values in the dynamically allocated object’s width and length variables. Figure 13-12 shows the state of the dynamically allocated object after these statements have executed. Figure 13-12 The rectPtr pointer variable holds the address of a dynamically allocated Rectangle object
A Rectangle object width: 10.0
address
length: 15.0
Line 12 deletes the object from memory and line 13 stores the address 0 in rectPtr. Recall from Chapter 9 that this prevents code from inadvertently using the pointer to access the area of memory that has been freed. It also prevents errors from occurring if delete is accidentally called on the pointer again. Program 13-3 is a modification of Program 13-2. In this program, kitchen, bedroom, and den are Rectangle pointers. They are used to dynamically allocate Rectangle objects. The output is the same as Program 13-2.
749
750
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)
757
758
Chapter 13
Program 13-4 22 23 24 25 26 27 28 29 30 31 32 33
Introduction to Classes
(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 > "What is your weight? "; cin mainOfficeRequest; Budget::mainOffice(mainOfficeRequest); Budget divisions[NUM_DIVISIONS]; // Array of Budget objects AuxiliaryOffice auxOffices[4]; // Array of AuxiliaryOffice // Get the budget requests for each division // and their auxiliary offices. for (count = 0; count < NUM_DIVISIONS; count++) { double budgetAmount; // To hold input // Get the request for the division office. cout width; // Store the width in the myRectangle object. while (tryAgain) { try { myRectangle.setWidth(width); // If no exception was thrown, then the // next statement will execute. tryAgain = false; }
16.1 Exceptions
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
catch (Rectangle::NegativeWidth) { cout > width; } } // Get the rectangle's length. 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 > letter; while (letter != 'Y' && letter != letter != 'N' && letter != { cout > (stream extraction), 84–85, 145
A abs library function, 131 abstract array data type case study, 795–799 abstract base classes, 942–946 abstract data type (ADT), 609–611 in the STL, 1007 access specifiers, 736–737 base class, 900–901 accessors, 740–741 accumulator, 280–281 actual arguments, 319
actual parameters, 319 addition operator (+), 62, 64, 93–94 address, 4, 15, 507 address operator (&), 507–509 ADT, see abstract data type aggregation, 872–877 has-a relationship, 875 UML, depicted in, 877 algebraic expressions, 95 algorithm, 7 STL, 1008–1010, 1014–1020 Alice software, 1171–1197 adding objects, 1176–1179 camera controls, 1179 creating methods, 1191–1192 creating variables/parameters, 1192–1194 creating world, 1176 deleting objects, 1184 downloading/installing, 1171 environment, 1173–1174 events, 1195–1197 instructions, copying/deleting, 1191 modifying objects, in Scene Editor mode, 1184–1186 playing world, 1175 primitive methods, 1181–1184 properties, 1180–1181 renaming of methods, 1192 selecting objects, 1180 single view/quad view modes, 1186–1187 variable assignment, 1195 Welcome to Alice! dialog box, 1171–1173 writing methods, 1187–1190 ALU, 3
1205
1206
Index
AND & bitwise operator, see Appendix J on the Student CD && logical operator, 199–201, 205–206 anonymous enum, 648 anonymous unions, 641–645 append member function, string class, 596 application software, 5–6 argument, 95–96, 319 command-line, see Appendix H on the Student CD default, 353–356 arithmetic expressions, 91–97 arithmetic logic unit (ALU), 3 arithmetic operators, 61–64 arrays accessing elements, 389–396 assigning one to another, 406–407 averaging values in, 408 binary search, 470–473 bounds checking, 396–398 bubble sort, 481–484 char, 88–89 compared to linked list, 1027–1028 comparing, 411–412 defining, 88, 387–388 duplicating, 541–543 element, 388 as function arguments, 415–424, 430–431 highest and lowest values, 409 implicit sizing, 402 initialization, 399–404, 429 initialization, partial, 401–402 inputting and outputting, 391–396 linear search, 467–470 loops, using with, 392 memory address, 406 memory requirements, 388–389 of objects, 784–786 off-by-one error, 398 parallel, 412–414 partially filled, 409–411 passing to functions, 415–424 and pointers, 516–520 printing contents of, 407–408 reading from a file into, 394–395 selection sort, 485–488 size declarator, 388, 390 strings, 433–435, 568–569 strings, initializing with, 403–404 of structures, 623–626 subscript, 389–390 summing values in, 408, 431–433 three or more dimensions, 435–436
two-dimensional, 426–433 using an enum with, 649–650 writing contents to a file, 395–396 arrow operator (->), 636, 748 ascending order, 481 ASCII, 49, 1199–1201 assign member function, string class, 596 assignment combined, 112–115 memberwise, 838–839 multiple, 112–113 operator (=), 59 statement, 40–41, 59 associative containers, 439, 1007–1008 associativity, 94, 164, 205–206, 1203 at member function string class, 596 vector, 450, 1013 atof library function, 577–578 atoi library function, 577–578 atol library function, 577–578 attributes, 730
B back member function, list, 1059 bad member function, file stream, 685 bad_alloc exception, 989–990 base case, recursion, 1112 base class, 896 abstract, 942–946 access specification, 900–901, 908–909 multiple, 949–954 pointers, 935–938 BASIC, 9 begin member function iterator, 1013 string class, 596 vector, 1013 binary digit (bit), 4, see also Appendix J on the Student CD binary files, 696–701 binary numbers, 7, see also Appendix J on the Student CD binary operator, 61 binary search, 470–473, 1125–1127 efficiency, 473 recursive version, 1125–1127 binary trees, 1145–1165 applications of, 1147 child nodes, 1145 creating, 1149–1150 deleting a node, 1156–1164 inorder traversal, 1152–1155 inserting a node, 1150–1152
leaf nodes, 1145 null address, 1145 operations, 1148–1165 postorder traversal, 1152–1155 preorder traversal, 1152–1155 root node, 1145 search trees, 1147 searching for a value in, 1152–1155 subtrees, 1146 template considerations, 1165 traversing, 1152–1155 tree pointer, 1145 binary_search algorithm (STL), 1008, 1014–1016 binding, 929 dynamic, 929 static, 929 bit, 4 working with, see Appendix J on the Student CD bitwise operators, see Appendix J on the Student CD block scope, 209 blueprints, classes as, 733–734 bool, 57, 176–177 returning from a function, 340–342 Boole, George, 57 Boolean expression, 57, 164 bounds checking, arrays, 396–398 brace, 31–32 break statement, 224, 290–292 bubble sort, 481–484 buffer, keyboard, 87 buffer overrun, 126 byte, 4
C C#, 9 C programming language, 8–9 C-strings, 51–53, 88, see also string appending one to another, 570, 572–573 arrays, 433–435 char array for holding, 88–89 comparing with strcmp, 213–217 concatenation, 570, 572–573 copying, 571–573 functions to handle, writing, 582–587 internal storage of, 566–569 length, getting, 569–570 library functions to work with, 569–576 null terminator, 51, 88, 566–567 numeric conversion functions, 577–582 searching within, 573–575 sorting, 217
Index
call, function, 95 calling a function, 310–315 capacity member function string class, 596 vector, 450, 1013 capitalization of variable names, 44 case conversion, character, 563–565 case statement, 222 case study abstract array data type, 795–799 Demetris Leadership Center, 474–480, 488–496 dollarFormat function, 598–599 General Crates, 137–140 Home Software Company, 598–599, 788–795 National Commerce Bank, 437–439 United Cause, 545–549 cast expression, 104 casting, type, 104–106 catch block, 973 catch key word, 973 central processing unit (CPU), 3–4 char, 49–53 char array, 88–89 character case conversion, 563–565 tolower function, 563 toupper function, 563 character literal, 50–52 character testing, 559–563 isalnum function, 560 isalpha function, 560 isdigit function, 560 islower function, 560 isprint function, 560 ispunct function, 560 isspace function, 560 isupper function, 560 cin, 17, 83–89 get member function, 128–131 getline member function, 127–128, 130, 568 ignore member function, 129–130 keyboard buffer, 87 reading a character, 127–129 reading a line of input, 127–128 reading multiple values, 85–86 setw manipulator with, 125–127 strings, reading, 88–89 width member function, see Appendix L on the Student CD circular linked list, 1058 class, 732–752 abstract, 942–946
access specifiers, 736–737 accessors, 740–741 aggregation, 872–877 arguments to constructors, 766–774 array of objects, 784–786 base, 896 base class access, 900–901, 908–909 as blueprint, 733–734 collaborations, 878–882 const member functions, 738, 741 constructor overloading, 778–782 constructors, 762–774 conversion, object, 870–872 copy constructor, 839–843 declaration, 736 default constructor, 766, 773–774, 782 derived, 896 destructors, 774–777, 782 dot operator (.), 741 dynamically allocated objects, 749–751 finding, 802–810 forward declaration, 835 friend functions, 833–837 getter function, 740 “has-a” relationship, 875 hierarchies, 921–927 implementation file, 754 include guard, 754–755 inheritance, 895–904 inline member functions, 759–761 instance, defining, 741 instance variables, 825–826 is-a relationship, 896, 938–939 member functions, defining, 739–740 memberwise assignment, 838–839 mutators, 740 objects vs., 732–734 operator overloading, 843–870 overloading member functions, 782 placement of public and private members, 738–739 pointers, 748–751 polymorphism, 927–941 private member functions, 782–784 private members, 736–737, 752–753 problem domain, 803 protected members, 904–907 public member functions, 737–738
public members, 736–737 responsibilities, identifying, 808 scope resolution operator (::), 740 separating specification from implementation, 753–759 setter function, 740 specification file, 753 stale data, avoiding, 748 static member functions, 830–833 static member variables, 826–830 templates, 997–1006 this pointer, 848 UML, 799–802 virtual functions, 929–935 whole-part relationship, 875 clear member function file stream objects, 685 string class, 596 vector, 447–448, 450, 1014 close member function, file stream objects, 143–144 closing a file, 143–144 cmath header file, 96, 131 COBOL, 9 code reuse, 308 coercion, 101 collaborations, class, 878–882 combined assignment operators, 112–115 command-line arguments, see Appendix H on the Student CD comment, 29, 68–69 //, 68–69 /* */, 68–69 multi-line, 68–69 single line, 68–69 compact disc (CD), 5 compare member function, string class, 597 compiler, 10–11, 674 concatenate, 570 conditional loop, 270 conditional operator, 218–221 conditionally-executed code, 169–170, 177–179 console, 33, 84 console output, 33 const, 107–109, 255, 529–531 member functions, 738, 741 constant pointers, 532–533 constants global, 344–349 named, 107–109 pointers to, 529–531
1207
1208
Index
constructor, 762–774 arguments passed to, 766–774 base and derived classes, in, 910–915 copy, 839–843 default, 766, 773–774, 782 default arguments with, 772 overloading, 778–782 containers, 439, 1007 associative, 1007–1008 sequence, 1007 continue statement, 292–293 control unit, 3 control variable, loop, 257 conversion by casting, 104–106 object, 870–872 string/numeric, 577–582 type, 101 copy constructor, 839–843 default, 843 copy member function, string class, 597 cos library function, 131 count algorithm (STL), 1009, 1016–1017 count-controlled loop, 270 counters, 263–265 cout, 17, 31, 33–37 fixed manipulator with, 121–124 left manipulator with, 123–124 precision member function, see Appendix L on the Student CD right manipulator with, 123–124 setf member function, see Appendix L on the Student CD setprecision manipulator with, 119–121, 124 setw manipulator with, 117–118, 124 showpoint manipulator with, 123–124 unsetf member function, see Appendix L on the Student CD width member function, see Appendix L on the Student CD CPU, 3–4 CRC cards, 881–882 cstdlib header file, 133, 367, 577 cstring header file, 214, 569 ctime header file, 133
D data hiding, 730–731 data type, 44–46 abstract, 609–611 bool, 57 casting, 104–106 char, 49–53 coercion, 101 conversion, 101, 104–106 demotion, 101 double, 54–57 float, 54–57 floating-point, 54–57 generic, 991 int, 45–46 integers, 44–48 long, 45–46 long double, 54–56 numeric, 44–45 primitive, 610 promotion, 101 ranking, 100–101 short, 45–46 size of, determining, 58 unsigned int, 45–46 unsigned long, 45–46 unsigneds hort, 45–46 database management systems, 673 debugging desk-checking, 20 hand-tracing, 135–136 stubs and drivers, 369–371 decimal point, digits displayed after, 119–123 decision structure, 168 declaration, 16 decode, 4 decrement operator (--), 249–254 mathematical expressions, in, 253 postfix mode, 250–253 prefix mode, 250–253 relational expressions, in, 253–254 default arguments, 353–356, 772 constructor, 766, 773–774, 782 copy constructor, 843 default statement, 223 #define directive, 109–111, 755 definition, variable, 16, 39–40, 209–211 delete operator, 536 Demetris Leadership Center case study, 474–480, 488–496 demotion, type, 101 depth of recursion, 1109 deque (STL type), 1007, 1097–1098 front member function, 1097
pop_front member function, 1097 push_back member function, 1097 dequeue operation, 1085–1088 dereferencing pointers, 513 derived class, 896 descending order, 481 designing a program, 17–21 desk-checking, 20 destructors, 774–777, 782 base and derived classes, in, 910–915 virtual, 939–941 digits displayed after decimal point, 119–123 direct recursion, 1118 directive, preprocessor, 30, 38 disk drive, 5 divide and conquer, 307–308 division integer, 62, 101–102 operator (/), 62, 93–94 remainder of, 62–63 by zero, 182, 971–972 do-while loop, 265–269, 287 with menus, 267–269 posttest, 265–266 dollarFormat function case study, 598–599 dot operator (.), 614, 741 double, 54–57 double precision, 54–55 doubly linked list, 1058 drivers and stubs, 369–371 dynamic binding, 929 dynamic memory allocation, 534–538 bad_alloc exception, 989–990 objects, 749–751, 766, 777 structures, 638–639 dynamic queues, 1085, 1093–1096 dynamic stacks, 1068, 1078–1082
E E notation, 54–55 EBCDIC, 49 editor, text, 10–11 element, 388 working with, 389–396 elements, language, 12–16 else, 182 trailing, 192, 194–195 empty member function list, 1059 stack, 1083 string class, 597 vector, 448–450, 1014 encapsulation, 130, 730
Index
end member function iterator, 1013 list, 1059 string class, 597 vector, 1014 end-of-file marker, 676 #endif directive, 754–755 endl, 35 endless loop, 258 enqueue operation, 1085–1088 enum, 645–655 anonymous, 648 assigning an integer to an enum variable, 647 combining declaration and definition, 655 comparing enumerators, 647 defining an enum variable, 646 enumerators, 646 math operators with, 649 outputting values with an enum, 651–652 scope and enumerators, 654 specifying enumerator values, 653–654 stepping through an array with, 649–650 enumerated data types, 645–655, see also enum enumerators, 646 eof member function, file stream, 685 equal-to operator (==), 164–166 erase member function list, 1059 string class, 597 vector, 1014 error logical, 20 recovering from, 982–984 syntax, 10 error testing, files, 685–687 escape sequence, 36 \\, 37 \', 37 \", 37 \a, 37 \b, 37 \n, 36–37 \r, 37 \t, 37 newline, 36 exception, 535, 971–990 bad_alloc, 989–990 catch block, 973 dynamic memory allocation, 535 extracting data from, 984–988 handler, 972 handling, 973–975
memory allocation error, 989–990 multiple, handling, 978–982 new operator, 535 not catching, 975 object-oriented handling, 975–978 recovering from errors, 982–984 rethrowing, 988–989 throw key word, 973 throw point, 973 throwing, 973 try block, 973 try/catch construct, 973–975 unwinding the stack, 988 exclusive OR, bitwise, see Appendix J on the Student CD executable code, 10–11 file, 10–11 execute, 4 exhaustive algorithms, 1136–1138 exit code, 367 exit library function, 366–367 EXIT_FAILURE constant, 367 EXIT_SUCCESS constant, 367 exp library function, 131 exponents, 95 expression, 91 algebraic, 95 arithmetic, 91–97 Boolean, 57, 164 cast, 104 initialization, for loop, 270–271, 275, 276–277 mathematical, 91–97 relational, 164 test, for loop, 270–271 update, for loop, 270–271, 275, 276–277
F factorial algorithm, 1112–1115 fail member function, file stream, 231, 685 fetch, 4 fetch/decode/execute cycle, 4 Fibonacci numbers, 1120–1122 field, bit, see Appendix J on the Student CD field width, 117, 125–126 file access flags, 675 ios::app, 675 ios::ate, 675 ios::badbit, 685 ios::binary, 675 ios::eofbit, 685 ios::failbit, 685 ios::goodbit, 685 ios::hardfail, 685
ios::in, 675 ios::out, 675 ios::trunc, 675 file buffer, 143 file I/O append mode, 675 binary files, 696–701 buffer, 143 closing a file, 143–144 end-of-file marker, 676 error testing, 231, 685–687 existence of a file, checking for, 678–679 file stream objects, 141, 674 fstream header file, 141 general process, 141 introduction, 140–148 multiple files, opening, 695 opening a file, 142–143 opening for both input and output, 714–716 output formatting, 680–683 passing stream objects to functions, 683–684 random-access, 706–714 read position, 146 reading a character, 692 reading a line, 689 reading from a file, 145–148 reading from a file into an array, 394–395 reading with a loop, 284–286 records, 702–706 rewinding, 713–714 setting a program up for, 141–142 writing a character, 694 writing an array to a file, 395–396 writing to a file, 144–145 file names, 679–681 file stream objects, 141 member functions, 688–693 passing to functions, 683–684 find algorithm (STL), 1009, 1018–1019 find member function, string class, 597 finding the classes, 802–810 first-in first out (FIFO), 1085 fixed manipulator, 121–123, 680 fixed point notation, 121–122 flag, 176–177 flash memory, 5 float, 54–55 floating-point data types, 54–57 comparing, 173–174 flowchart, 19, see also Appendix D on the Student CD
1209
1210
Index
fmod library function, 131 for loop, 270–279, 287 arrays and, 392 header, 270 initialization expression, 270–271, 275, 276–277 instead of while or do-while, 273–274 pretest, 274 test expression, 270–271 update expression, 270–271, 275, 276–277 user-controlled, 275–276 for_each algorithm (STL), 1009, 1019–1020 formal argument, 319 formatted input, 125–130 formatting output, 116–124 FORTRAN, 9 forward declaration, 835 friend class, 837 functions, 833–837 key word, 833 front member function deque, 1097 list, 1059 vector, 1014 fstream header file, 141–142 fstream objects, 675 functions, 30 arguments, 95–96, 319 body, 309 bool value, returning, 340–342 call, 95, 310–315, 334–337 code reuse, 308 declaration, 317 default arguments, 353–356, 771 definition, 309–310 file stream objects as arguments, 683–684 friend, 833–837 generic, 990 header, 309 inline, 759–761 local variables, 333, 342–344 main, 30–31 member, 730 modular programming, 307–308 names, 309 overloading, 362–366 overriding, 939 parameter list, 309 parameters, 319 passing by reference, 356–361, 525 passing by value, 324–325 pointers as parameters, 525–529 prototypes, 317–318 pure virtual, 942
recursive, 1107 redefining base class, 917–921 reference variables as parameters, 356–361 return statement, 330–331, 333 return type, 309 returning a structure, 633–635 returning a value from, 332–342 returning pointers from, 538–540 sending data into, 319–323 signature, 363 static local variables, 350–353 static member, 830–833 string handling, 582–587 structures as arguments, 630–633 stubs and drivers, 369–371 templates, 990–997 value-returning, 332–342 virtual, 929–935, 942 void, 309–310
G g++ command, 10 General Crates case study, 137–140 generalization and specialization, 895 generic function, 990 type, 991 get member function cin, 128–131 file streams, 692 getline member function cin, 127–128, 130, 568 file streams, 689 getter function, 740 global variables and constants, 344–349 good member function, file stream, 685 greater-than operator (>), 164–166 greater-than or equal-to operator (>=), 164–166 greatest common divisor (GCD), 1119–1120
H hand-tracing, 135–136 handler, exception, 972 Hanoi, Towers of, 1128–1131 hard disk, 5 hardware, 2–5 CPU, 2–4 input devices, 2, 5 main memory, 2, 4 output devices, 2, 5 secondary storage, 2, 4–5 “has-a” relationship, 875 head, linked list, 1029 header file, 30 cmath, 96, 131
cstdlib, 133, 367, 577 cstring, 214, 569 ctime, 133 fstream, 141–142 iostream, 30, 38–39 prestandard style, 71 string, 588 hexadecimal literals, 48 hierarchies, class, 921–927 hierarchy chart, 19 high-level languages, 8 Hoare, C.A.R., 1131 Home Software Company case study, 598–599, 788–795
I IDE, 11 identifiers, 43–44 capitalization, 44 legal, 44 if/else statement, 181–183 if/elseif statement, 191–195 trailing else, 192, 194–195 if statement, 168–179 conditionally-executed code, 169–170, 177–179 expanding, 177–179 floating point comparisons, 173–174 indentation, 173 nested, 184–191 programming style, 173 #ifndef directive, 754–755 ifstream objects, 142, 674, 678 >> used with, 145 close member function, 143–144 fail member function, 231 open member function, 142–143 ignore member function, cin, 129–130 implementation file, class, 754 implicit sizing, arrays, 402 #include directive, 30, 38–39, 757 include file directory, 757 include guard, 754–755 increment operator (++), 249–254 mathematical expressions, in, 253 postfix mode, 250–253 prefix mode, 250–253 relational expressions, in, 253–254 indentation, 69–70, 173, 259 indirect recursion, 1118 indirection operator, 513 infinite loop, 258 inheritance, 895–904 base class, 896 class hierarchies, 921–927
Index
constructors and destructors, 910–915 derived class, 896 “is-a” relationship, 896 multiple, 949–954 redefining functions, 917–921 and templates, 1003–1006 initialization, 60 arrays, 399–404, 429 arrays of objects, 785 list, 399 partial, array, 401–402 pointers, 522 structure, 619–622 structure array, 626 variable, 60 initialization expression (for loop), 270–271, 275, 276–277 inline expansion, 761 member functions, 759–761 inorder traversal, binary trees, 1152–1155 input, 16–17 with cin, 83–89 devices, 5 formatted, 125–130 validation, 197, 207–208, 261–263 input-output stream library, 38 insert member function string class, 597 vector, 1014 insert member function list, 1059 instance, 613 class, 741 variables, 825–826 instantiation, 741 int, 45–46 integer data types, 44–45 division, 62, 101–102 IntegerList class, 795–799 integrated development environment (IDE), 11 ios::app access flag, 675 ios::ate access flag, 675 ios::badbit status flag, 685 ios::binary access flag, 675, 697 ios::eofbit status flag, 685 ios::failbit status flag, 685 ios::goodbit status flag, 685 ios::hardfail status flag, 685 ios::in access flag, 675 ios::out access flag, 675 iostream header file, 30, 38–39 ios::trunc access flag, 675 “is-a” relationship, 896, 938–939
isalnum library function, 560 isalpha library function, 560 isdigit library function, 560 islower library function, 560 isprint library function, 560 ispunct library function, 560 isspace library function, 560 isupper library function, 560 iteration, loop, 256 iterators, 1007–1008 [ ] operator, 1010–1013 begin member function, 1013 bidirectional, 1008 end member function, 1013 forward, 1008 input, 1008 output, 1008 random-access, 1008 itoa library function, 577–579
J Java, 9 JavaScript, 9
K key words, 13–14, 43–44 keyboard buffer, 87 input with cin, 83–89
L language elements, 12–16 last-in-first-out (LIFO), 1067 left manipulator, 123–124 length member function, string class, 594–595, 597 less-than operator (> and