Starting out with C from control structures
through objects Eighth Edition Tony Gaddis
download
https://ebookname.com/product/starting-out-with-c-from-control-
structures-through-objects-eighth-edition-tony-gaddis/
Get Instant Ebook Downloads – Browse at https://ebookname.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
Starting Out with Visual C 2012 3; global Edition Tony
Gaddis
https://ebookname.com/product/starting-out-with-
visual-c-2012-3-global-edition-tony-gaddis/
Starting Out With Python 3rd Edition Tony Gaddis
https://ebookname.com/product/starting-out-with-python-3rd-
edition-tony-gaddis/
Starting Out With Visual Basic 2008 Update 4th Edition
Edition Gaddis
https://ebookname.com/product/starting-out-with-visual-
basic-2008-update-4th-edition-edition-gaddis/
Tundra 1st Edition Peter D. Moore
https://ebookname.com/product/tundra-1st-edition-peter-d-moore/
Wittgenstein and the Human Form of Life 1st Edition
Oswald Hanfling
https://ebookname.com/product/wittgenstein-and-the-human-form-of-
life-1st-edition-oswald-hanfling/
Contemporary Debates in Philosophy of Biology
Contemporary Debates in Philosophy 1st Edition
Francisco J. Ayala
https://ebookname.com/product/contemporary-debates-in-philosophy-
of-biology-contemporary-debates-in-philosophy-1st-edition-
francisco-j-ayala/
Evil Andrew P. Chignell
https://ebookname.com/product/evil-andrew-p-chignell/
The Macroeconomics of Global Imbalances European and
Asian Perspectives 1st Edition Marc Uzan
https://ebookname.com/product/the-macroeconomics-of-global-
imbalances-european-and-asian-perspectives-1st-edition-marc-uzan/
Worker Absenteeism and Sick Pay 1st Edition John Treble
https://ebookname.com/product/worker-absenteeism-and-sick-
pay-1st-edition-john-treble/
Plant Breeding Reviews Volume 20 1st Edition Jules
Janick (Editor)
https://ebookname.com/product/plant-breeding-reviews-
volume-20-1st-edition-jules-janick-editor/
C++
EIGHTH ED ITIO N
STARTING OUT WITH
C++
From Control Structures
through Objects
This page intentionally left blank
C++
EIGHTH ED ITIO N
STARTING OUT WITH
C++
From Control Structures
through Objects
Tony Gaddis
Haywood Community College
Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear on the
Credits page in the endmatter of this textbook.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., publishing as Addison-Wesley All rights reserved.
Manufactured in the United States of America. This publication is protected by Copyright, and permission
should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or
transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To
obtain permission(s) to use material from this work, please submit a written request to Pearson Education,
Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458 or you may fax your
request to 201 236-3290.
Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and the publisher was aware of a trademark claim, the
designations have been printed in initial caps or all caps.
Library of Congress Cataloging-in-Publication Data
Gaddis, Tony.
Starting out with C++ : from control structures through objects/Tony Gaddis.—Eighth edition.
pages cm
Includes bibliographical references and index.
Online the following appendices are available at www.pearsonhighered.com/gaddis: Appendix D:
Introduction to flowcharting; Appendix E: Using UML in class design; Appendix F: Namespaces; Appendix G:
Writing managed C++ code for the .net framework; Appendix H: Passing command line arguments; Appendix
I: Header file and library function reference; Appendix J: Binary numbers and bitwise operations; Appendix K:
Multi-source file programs; Appendix L: Stream member functions for formatting; Appendix M: Introduction
to Microsoft Visual C++ 2010 express edition; Appendix N: Answers to checkpoints; and Appendix O:
Solutions to odd-numbered review questions.
ISBN-13: 978-0-13-376939-5
ISBN-10: 0-13-376939-9
1. C++ (Computer program language) I. Title. II. Title: From control structures through objects.
QA76.73.C153G33 2014b
005.13’3—dc23
2014000213
10 9 8 7 6 5 4 3 2 1
Editorial Director: Marcia Horton
Acquisitions Editor: Matt Goldstein
Program Manager: Kayla Smith-Tarbox
Director of Marketing: Christy Lesko
Marketing Coordinator: Kathryn Ferranti
Marketing Assistant: Jon Bryant
Senior Managing Editor: Scott Disanno
Senior Project Manager: Marilyn Lloyd
Operations Supervisor: Vincent Scelta
Operations Specialist: Linda Sager
Art Director, Cover: Jayne Conte
Text Designer: Joyce Cosentino Wells
Cover Designer: Bruce Kenselaar
Manager, Visual Research: Karen Sanatar
Permissions Supervisor: Michael Joyce
Permission Administrator: Jenell Forschler
Cover Image: Sergio37_120/Fotolia
Media Project Manager: Renata Butera
Full-Service Project Manager: Jogender Taneja
Aptara®, Inc.
Full-Service Vendor: Aptara®, Inc.
Printer/Binder: Courier Kendallville
Cover Printer: Lehigh-Phoenix Color/Hagerstown
ISBN 13: 978-0-13-376939-5
ISBN 10: 0-13-376939-9
v
Contents at a Glance
Preface xv
CHAPTER 1 Introduction to Computers and Programming 1
CHAPTER 2 Introduction to C++ 27
CHAPTER 3 Expressions and Interactivity 83
CHAPTER 4 Making Decisions 149
CHAPTER 5 Loops and Files 227
CHAPTER 6 Functions 299
CHAPTER 7 Arrays 375
CHAPTER 8 Searching and Sorting Arrays 457
CHAPTER 9 Pointers 495
CHAPTER 10 Characters, C-Strings, and More About the string Class 547
CHAPTER 11 Structured Data 599
CHAPTER 12 Advanced File Operations 657
CHAPTER 13 Introduction to Classes 711
CHAPTER 14 More About Classes 811
CHAPTER 15 Inheritance, Polymorphism, and Virtual Functions 891
CHAPTER 16 Exceptions, Templates, and the Standard Template
Library (STL) 971
CHAPTER 17 Linked Lists 1025
CHAPTER 18 Stacks and Queues 1063
CHAPTER 19 Recursion 1121
CHAPTER 20 Binary Trees 1155
Appendix A: Getting Started with Alice 1185
Appendix B: The ASCII Character Set 1211
Appendix C: Operator Precedence and Associativity 1213
Quick References 1215
vi Contents at a Glance
Index 1217
Credit 1237
Online The following appendices are available at www.pearsonhighered.com/gaddis.
Appendix D: Introduction to Flowcharting
Appendix E: Using UML in Class Design
Appendix F: Namespaces
Appendix G: Passing Command Line Arguments
Appendix H: Header File and Library Function Reference
Appendix I: Binary Numbers and Bitwise Operations
Appendix J: Multi-Source File Programs
Appendix K: Stream Member Functions for Formatting
Appendix L: Answers to Checkpoints
Appendix M: Solutions to Odd-Numbered Review Questions
Preface xv
CHAPTER 1 Introduction to Computers and Programming 1
1.1 Why Program? 1
1.2 Computer Systems: Hardware and Software 2
1.3 Programs and Programming Languages 8
1.4 What Is a Program Made of? 14
1.5 Input, Processing, and Output 17
1.6 The Programming Process 18
1.7 Procedural and Object-Oriented Programming 22
CHAPTER 2 Introduction to C++ 27
2.1 The Parts of a C++ Program 27
2.2 The cout Object 31
2.3 The #include Directive 36
2.4 Variables and Literals 37
2.5 Identifiers 41
2.6 Integer Data Types 42
2.7 The char Data Type 48
2.8 The C++ string Class 52
2.9 Floating-Point Data Types 54
2.10 The bool Data Type 57
2.11 Determining the Size of a Data Type 58
2.12 Variable Assignments and Initialization 59
2.13 Scope 61
2.14 Arithmetic Operators 61
2.15 Comments 69
2.16 Named Constants 71
2.17 Programming Style 73
vii
Contents
viii Contents
CHAPTER 3 Expressions and Interactivity 83
3.1 The cin Object 83
3.2 Mathematical Expressions 89
3.3 When You Mix Apples and Oranges: Type Conversion 98
3.4 Overflow and Underflow 100
3.5 Type Casting 101
3.6 Multiple Assignment and Combined Assignment 104
3.7 Formatting Output 108
3.8 Working with Characters and string Objects 118
3.9 More Mathematical Library Functions 124
3.10 Focus on Debugging: Hand Tracing a Program 130
3.11 Focus on Problem Solving: A Case Study 132
CHAPTER 4 Making Decisions 149
4.1 Relational Operators 149
4.2 The if Statement 154
4.3 Expanding the if Statement 162
4.4 The if/else Statement 166
4.5 Nested if Statements 169
4.6 The if/else if Statement 176
4.7 Flags 181
4.8 Logical Operators 182
4.9 Checking Numeric Ranges with Logical Operators 189
4.10 Menus 190
4.11 Focus on Software Engineering: Validating User Input 193
4.12 Comparing Characters and Strings 195
4.13 The Conditional Operator 199
4.14 The switch Statement 202
4.15 More About Blocks and Variable Scope 211
CHAPTER 5 Loops and Files 227
5.1 The Increment and Decrement Operators 227
5.2 Introduction to Loops: The while Loop 232
5.3 Using the while Loop for Input Validation 239
5.4 Counters 241
5.5 The do-while Loop 242
5.6 The for Loop 247
5.7 Keeping a Running Total 257
5.8 Sentinels 260
5.9 Focus on Software Engineering: Deciding Which Loop to Use 261
5.10 Nested Loops 262
5.11 Using Files for Data Storage 265
5.12 Optional Topics: Breaking and Continuing a Loop 284
CHAPTER 6 Functions 299
6.1 Focus on Software Engineering: Modular Programming 299
6.2 Defining and Calling Functions 300
6.3 Function Prototypes 309
6.4 Sending Data into a Function 311
Contents ix
6.5 Passing Data by Value 316
6.6 Focus on Software Engineering: Using Functions in a
Menu-Driven Program 318
6.7 The return Statement 322
6.8 Returning a Value from a Function 324
6.9 Returning a Boolean Value 332
6.10 Local and Global Variables 334
6.11 Static Local Variables 342
6.12 Default Arguments 345
6.13 Using Reference Variables as Parameters 348
6.14 Overloading Functions 354
6.15 The exit() Function 358
6.16 Stubs and Drivers 361
CHAPTER 7 Arrays 375
7.1 Arrays Hold Multiple Values 375
7.2 Accessing Array Elements 377
7.3 No Bounds Checking in C++ 384
7.4 Array Initialization 387
7.5 The Range-Based for Loop 392
7.6 Processing Array Contents 396
7.7 Focus on Software Engineering: Using Parallel Arrays 404
7.8 Arrays as Function Arguments 407
7.9 Two-Dimensional Arrays 418
7.10 Arrays with Three or More Dimensions 425
7.11 Focus on Problem Solving and Program Design: A Case Study 427
7.12 If You Plan to Continue in Computer Science: Introduction to the
STL vector 429
CHAPTER 8 Searching and Sorting Arrays 457
8.1 Focus on Software Engineering: Introduction to Search Algorithms 457
8.2 Focus on Problem Solving and Program Design: A Case Study 463
8.3 Focus on Software Engineering: Introduction to Sorting Algorithms 470
8.4 Focus on Problem Solving and Program Design: A Case Study 477
8.5 If You Plan to Continue in Computer Science: Sorting and
Searching vectors 485
CHAPTER 9 Pointers 495
9.1 Getting the Address of a Variable 495
9.2 Pointer Variables 497
9.3 The Relationship Between Arrays and Pointers 504
9.4 Pointer Arithmetic 508
9.5 Initializing Pointers 510
9.6 Comparing Pointers 511
9.7 Pointers as Function Parameters 513
9.8 Focus on Software Engineering: Dynamic Memory Allocation 522
9.9 Focus on Software Engineering: Returning Pointers from Functions 526
9.10 Using Smart Pointers to Avoid Memory Leaks 533
9.11 Focus on Problem Solving and Program Design: A Case Study 536
x Contents
CHAPTER 10 Characters, C-Strings, and More About the string Class 547
10.1 Character Testing 547
10.2 Character Case Conversion 551
10.3 C-Strings 554
10.4 Library Functions for Working with C-Strings 558
10.5 C-String/Numeric Conversion Functions 569
10.6 Focus on Software Engineering: Writing Your Own
C-String-Handling Functions 575
10.7 More About the C++ string Class 581
10.8 Focus on Problem Solving and Program Design: A Case Study 590
CHAPTER 11 Structured Data 599
11.1 Abstract Data Types 599
11.2 Focus on Software Engineering: Combining Data into Structures 601
11.3 Accessing Structure Members 604
11.4 Initializing a Structure 608
11.5 Arrays of Structures 611
11.6 Focus on Software Engineering: Nested Structures 613
11.7 Structures as Function Arguments 617
11.8 Returning a Structure from a Function 620
11.9 Pointers to Structures 623
11.10 Focus on Software Engineering: When to Use ., When to Use ->,
and When to Use * 626
11.11 Unions 628
11.12 Enumerated Data Types 632
CHAPTER 12 Advanced File Operations 657
12.1 File Operations 657
12.2 File Output Formatting 663
12.3 Passing File Stream Objects to Functions 665
12.4 More Detailed Error Testing 667
12.5 Member Functions for Reading and Writing Files 670
12.6 Focus on Software Engineering: Working with Multiple Files 678
12.7 Binary Files 680
12.8 Creating Records with Structures 685
12.9 Random-Access Files 689
12.10 Opening a File for Both Input and Output 697
CHAPTER 13 Introduction to Classes 711
13.1 Procedural and Object-Oriented Programming 711
13.2 Introduction to Classes 718
13.3 Defining an Instance of a Class 723
13.4 Why Have Private Members? 736
13.5 Focus on Software Engineering: Separating Class Specification
from Implementation 737
13.6 Inline Member Functions 743
13.7 Constructors 746
13.8 Passing Arguments to Constructors 750
Contents xi
13.9 Destructors 758
13.10 Overloading Constructors 762
13.11 Private Member Functions 765
13.12 Arrays of Objects 767
13.13 Focus on Problem Solving and Program Design: An OOP Case Study 771
13.14 Focus on Object-Oriented Programming: Simulating Dice with Objects 778
13.15 Focus on Object-Oriented Programming: Creating an Abstract Array
Data Type 782
13.16 Focus on Object-Oriented Design: The Unified Modeling Language (UML) 785
13.17 Focus on Object-Oriented Design: Finding the Classes and Their
Responsibilities 788
CHAPTER 14 More About Classes 811
14.1 Instance and Static Members 811
14.2 Friends of Classes 819
14.3 Memberwise Assignment 824
14.4 Copy Constructors 825
14.5 Operator Overloading 831
14.6 Object Conversion 858
14.7 Aggregation 860
14.8 Focus on Object-Oriented Design: Class Collaborations 865
14.9 Focus on Object-Oriented Programming: Simulating the Game
of Cho-Han 869
CHAPTER 15 Inheritance, Polymorphism, and Virtual Functions 891
15.1 What Is Inheritance? 891
15.2 Protected Members and Class Access 900
15.3 Constructors and Destructors in Base and Derived Classes 906
15.4 Redefining Base Class Functions 918
15.5 Class Hierarchies 923
15.6 Polymorphism and Virtual Member Functions 929
15.7 Abstract Base Classes and Pure Virtual Functions 945
15.8 Multiple Inheritance 952
CHAPTER 16 Exceptions, Templates, and the Standard Template
Library (STL) 971
16.1 Exceptions 971
16.2 Function Templates 990
16.3 Focus on Software Engineering: Where to Start When Defining Templates 996
16.4 Class Templates 996
16.5 Introduction to the Standard Template Library (STL) 1005
CHAPTER 17 Linked Lists 1025
17.1 Introduction to the Linked List ADT 1025
17.2 Linked List Operations 1027
17.3 A Linked List Template 1043
17.4 Variations of the Linked List 1055
17.5 The STL list Container 1056
xii Contents
CHAPTER 18 Stacks and Queues 1063
18.1 Introduction to the Stack ADT 1063
18.2 Dynamic Stacks 1080
18.3 The STL stack Container 1091
18.4 Introduction to the Queue ADT 1093
18.5 Dynamic Queues 1105
18.6 The STL deque and queue Containers 1112
CHAPTER 19 Recursion 1121
19.1 Introduction to Recursion 1121
19.2 Solving Problems with Recursion 1125
19.3 Focus on Problem Solving and Program Design: The Recursive
gcd Function 1133
19.4 Focus on Problem Solving and Program Design: Solving Recursively
Defined Problems 1134
19.5 Focus on Problem Solving and Program Design: Recursive Linked List
Operations 1135
19.6 Focus on Problem Solving and Program Design: A Recursive Binary
Search Function 1139
19.7 The Towers of Hanoi 1141
19.8 Focus on Problem Solving and Program Design: The QuickSort Algorithm 1144
19.9 Exhaustive Algorithms 1148
19.10 Focus on Software Engineering: Recursion vs. Iteration 1151
CHAPTER 20 Binary Trees 1155
20.1 Definition and Applications of Binary Trees 1155
20.2 Binary Search Tree Operations 1158
20.3 Template Considerations for Binary Search Trees 1175
Appendix A: Getting Started with Alice 1185
Appendix B: The ASCII Character Set 1211
Appendix C: Operator Precedence and Associativity 1213
Quick References 1215
Index 1217
Credit 1237
Online The following appendices are available at www.pearsonhighered.com/gaddis.
Appendix D: Introduction to Flowcharting
Appendix E: Using UML in Class Design
Appendix F: Namespaces
Appendix G: Passing Command Line Arguments
Appendix H: Header File and Library Function Reference
Appendix I: Binary Numbers and Bitwise Operations
Appendix J: Multi-Source File Programs
Appendix K: Stream Member Functions for Formatting
Appendix L: Answers to Checkpoints
Appendix M: Solutions to Odd-Numbered Review Questions
LOCATION OF VIDEONOTES IN THE TEXT
Chapter 1 Introduction to Flowcharting, p. 20
Designing a Program with Pseudocode, p. 20
Designing the Account Balance Program, p. 25
Predicting the Result of Problem 33, p. 26
Chapter 2 Using cout, p. 31
Variabe Definitions, p. 37
Assignment Statements and Simple Math Expressions, p. 62
Solving the Restaurant Bill Problem, p. 80
Chapter 3 Reading Input with cin, p. 83
Formatting Numbers with setprecision, p. 111
Solving the Stadium Seating Problem, p. 142
Chapter 4 The if Statement, p. 154
The if/else statement, p. 166
The if/else if Statement, p. 176
Solving the Time Calculator Problem, p. 221
Chapter 5 The while Loop, p. 232
The for Loop, p. 247
Reading Data from a File, p. 274
Solving the Calories Burned Problem, p. 293
Chapter 6 Functions and Arguments, p. 311
Value-Returnlng Functions, p. 324
Solving the Markup Problem, p. 366
Chapter 7 Accessing Array Elements With a Loop, p. 380
Passing an Array to a Function, p. 407
Solving the Chips and Salsa Problem, p. 448
Chapter 8 The Binary Search, p. 460
The Selection Sort, p. 474
Solving the Charge Account Validation Modification Problem, p. 492
Chapter 9 Dynamically Allocating an Array, p. 523
Solving the Pointer Rewrite Problem, p. 545
Chapter 10 Writing a C-String-Handling Function, p. 575
More About the string Class, p. 581
Solving the Backward String Problem, p. 594
(continued on the next page)
LOCATION OF VIDEONOTES IN THE TEXT (continued)
Chapter 11 Creating a Structure, p. 601
Passing a Structure to a Function, p. 617
Solving the Weather Statistics Problem, p. 652
Chapter 12 Passing File Stream Objects to Functions, p. 665
Working with Multiple Files, p. 678
Solving the File Encryption Filter Problem, p. 708
Chapter 13 Writing a Class, p. 718
Defining an Instance of a Class, p. 723
Solving the Employee Class Problem, p. 802
Chapter 14 Operator Overloading, p. 831
Class Aggregation, p. 860
Solving the NumDays Problem, p. 885
Chapter 15 Redefining a Base Class Function in a Derived Class, p. 918
Polymorphism, p. 929
Solving the Employee and Production-Worker Classes Problem, p. 963
Chapter 16 Throwing an Exception, p. 972
Handling an Exception, p. 972
Writing a Function Template, p. 990
Storing Objects in a vector, p. 1010
Solving the Exception Project Problem, p. 1024
Chapter 17 Appending a Node to a Linked List, p. 1028
Inserting a Node in a Linked List, p. 1035
Deleting a Node from a Linked List, p. 1039
Solving the Member Insertion by Position Problem, p. 1061
Chapter 18 Storing Objects in an STL stack, p. 1091
Storing Objects in an STL queue, p. 1114
Solving the File Compare Problem, p. 1119
Chapter 19 Reducing a Problem with Recursion, p. 1126
Solving the Recursive Multiplication Problem, p. 1153
Chapter 20 Inserting a Node in a Binary Tree, p. 1160
Deleting a Node from a Binary Tree, p. 1166
Solving the Node Counter Problem, p. 1182
Welcome to Starting Out with C++: From Control Structures through Objects, 8th edition.
This book is intended for use in a two-semester C++ programming sequence, or an acceler-
ated 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 intro-
ductory programming course. This text is rich in example programs that are concise, practi-
cal, 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 Eighth Edition
C++11 is the latest standard version of the C++ language. In previous years, while the stan-
dard was being developed, it was known as C++0x. In August 2011, it was approved by
the International Standards Organization (ISO), and the name of the standard was officially
changed to C++11. Most of the popular compilers now support the C++11 standard.
The new C++11 standard was the primary motivation behind this edition. Although this
edition introduces many of the new language features, a C++11 compiler is not strictly
required to use the book. As you progress through the book, you will see C++11 icons in the
margins, next to the new features that are introduced. Programs appearing in sections that
are not marked with this icon will still compile using an older compiler.
Here is a summary of the new C++11 topics that are introduced in this edition:
● The auto key word is introduced as a way to simplify complex variable definitions.
The auto key word causes the compiler to infer a variable’s data type from its initial-
ization value.
● The long long int and unsigned long long int data types, and the LL literal
suffix are introduced.
● Chapter 5 shows how to pass a string object directly to a file stream object’s open
member function, without the need to call the c_str() member function. (A discus-
sion of the c_str()function still exists for anyone using a legacy compiler.)
Preface
xv
xvi Preface
● The range-based for loop is introduced in Chapter 7. This new looping mechanism
automatically iterates over each element of an array, vector, or other collection,
without the need of a counter variable or a subscript.
● Chapter 7 shows how a vector can be initialized with an initialization list.
● The nullptr key word is introduced as the standard way of representing a null
pointer.
● Smart pointers are introduced in Chapter 9, with an example of dynamic memory
allocation using unique_ptr.
● Chapter 10 discusses the new, overloaded to_string functions for converting numeric
values to string objects.
● The string class’s new back() and front() member functions are included in
Chapter 10’s overview of the string class.
● Strongly typed enums are discussed in Chapter 11.
● Chapter 13 shows how to use the smart pointer unique_ptr to dynamically allocate
an object.
● Chapter 15 discusses the override key word and demonstrates how it can help prevent
subtle overriding errors.The final key word is discussed as a way of preventing a virtual
member function from being overridden.
In addition to the C++11 topics, the following general improvements were made:
● Several new programming problems have been added to the text, and many of the
existing programming problems have been modified to make them unique from previ-
ous editions.
● The discussion of early, historic computers in Chapter 1 is expanded.
● The discussion of literal values in Chapter 2 is improved.
● The introduction of the char data type in Chapter 2 is reorganized to use character
literals in variable assignments before using ASCII values in variable assignments.
● The discussion of random numbers in Chapter 3 is expanded and improved, with the
addition of a new In the Spotlight section.
● A new Focus on Object-Oriented Programming section has been added to Chapter 13,
showing how to write a class that simulates dice.
● A new Focus on Object-Oriented Programming section has been added to Chapter 14,
showing an object-oriented program that simulates the game of Cho-Han. The program
uses objects for the dealer, two players, and a pair of dice.
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.
Preface xvii
Chapter 8
Searching and
Sorting Arrays
Chapter 9
Pointers
Chapter 10
Characters, Strings,
and the string Class
Chapter 12
Advanced File
Operations*
Chapter 20
Binary Trees
Chapters 2–7
Basic Language
Elements
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
*A few subtopics in
Chapter 12 require
Chapters 9 and 11.
Chapter 1
Introduction
Figure P-1
xviii Preface
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 Chap-
ter 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 fun-
damentals of programming, problem solving, and software design. The components of pro-
grams, 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, vari-
able declarations, constants, comments, program output, simple arithmetic operations, and
C-strings. Programming style conventions are introduced and good programming style
is modeled here, as it is throughout the text. An optional section explains the difference
between ANSI standard and pre-standard C++ programs.
Chapter 3: Expressions and Interactivity
In this chapter the student learns to write programs that input and handle numeric, char-
acter, and string data. The use of arithmetic operators and the creation of mathematical
expressions are covered in greater detail, with emphasis on operator precedence. Debug-
ging is introduced, with a section on hand tracing a program. Sections are also included on
simple output formatting, on data type conversion and type casting, and on using library
functions that work with numbers.
Chapter 4: Making Decisions
Here the student learns about relational operators, relational expressions and how to con-
trol the flow of a program with the if, if/else, and if/else if statements. The condi-
tional 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.
Preface xix
Chapter 5: Loops and Files
This chapter covers repetition control structures. The while loop, do-while loop, and for
loop are taught, along with common uses for these devices. Counters, accumulators, run-
ning totals, sentinels, and other application-related topics are discussed. Sequential file I/O
is also introduced. The student learns to read and write text files, and use loops to process
the data in a file.
Chapter 6: Functions
In this chapter the student learns how and why to modularize programs, using both void
and value returning functions. Argument passing is covered, with emphasis on when argu-
ments 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 algo-
rithms. There is also a section on sorting and searching STL vector objects.
Chapter 9: Pointers
This chapter explains how to use pointers. Pointers are compared to and contrasted with
reference variables. Other topics include pointer arithmetic, initialization of pointers, rela-
tional comparison of pointers, pointers and arrays, pointers and functions, dynamic mem-
ory allocation, and more.
Chapter 10: Characters, C-strings, and More About the string Class
This chapter discusses various ways to process text at a detailed level. Library functions for
testing and manipulating characters are introduced. C-strings are discussed, and the tech-
nique of storing C-strings in char arrays is covered. An extensive discussion of the string
class methods is also given.
Chapter 11: Structured Data
The student is introduced to abstract data types and taught how to create them using struc-
tures, unions, and enumerated data types. Discussions and examples include using pointers
to structures, passing structures to functions, and returning structures from functions.
xx Preface
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 fun-
damental 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 pres-
ents 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 assign-
ment, and copy constructors are discussed. The chapter also includes in-depth sections on
operator overloading, object conversion, and object aggregation. There is also a section on
class collaborations and the use of CRC cards.
Chapter 15: Inheritance, Polymorphism, and Virtual Functions
The study of classes continues in this chapter with the subjects of inheritance, polymor-
phism, and virtual member functions. The topics covered include base and derived class con-
structors and destructors, virtual member functions, base class pointers, static and dynamic
binding, multiple inheritance, and class hierarchies.
Chapter 16: Exceptions, Templates, and the Standard
Template Library (STL)
The student learns to develop enhanced error trapping techniques using exceptions. Discus-
sion 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
Preface xxi
denominator (GCD), performing a binary search, and sorting (QuickSort). The classic Tow-
ers 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.
The following appendices are available online at www.pearsonhighered.com/gaddis.
Appendix D: Introduction to Flowcharting
A brief introduction to flowcharting. This tutorial discusses sequence, selection, case, repeti-
tion, 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: Passing Command Line Arguments
Teaches the student how to write a C++ program that accepts arguments from the command
line. This appendix will be useful to students working in a command line environment, such
as Unix, Linux, or the Windows command prompt.
Appendix H: Header File and Library Function Reference
This appendix provides a reference for the C++ library functions and header files discussed
in the book.
Appendix I: Binary Numbers and Bitwise Operations
A guide to the C++ bitwise operators, as well as a tutorial on the internal storage of integers.
xxii Preface
Appendix J: 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 K: Stream Member Functions for Formatting
Covers stream member functions for formatting such as setf.
Appendix L: Answers to Checkpoints
Students may test their own progress by comparing their answers to the checkpoint exer-
cises against this appendix. The answers to all Checkpoints are included.
Appendix M: Solutions to Odd-Numbered Review Questions
Another tool that students can use to gauge their progress.
Features of the Text
Concept Each major section of the text starts with a concept statement.
Statements This statement summarizes the ideas of the section.
Example Programs The text has hundreds of complete example programs, each
designed to highlight the topic currently being studied. In most
cases, these are practical, real-world examples. Source code for
these programs is provided so that students can run the programs
themselves.
Program Output After each example program there is a sample of its screen
output. This immediately shows the student how the program
should function.
In the Spotlight Each of these sections provides a programming problem and a
detailed, step-by-step analysis showing the student how to
solve it.
VideoNotes A series of online videos, developed specifically for this book, is
available for viewing at www.pearsonhighered.com/gaddis.
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 can
be downloaded from the book’s Companion Web site at www.
pearsonhighered.com/gaddis. This allows students to check how
well they have learned a new topic.
Notes Notes appear at appropriate places throughout the text. They are
short explanations of interesting or often misunderstood points
relevant to the topic at hand.
Preface xxiii
Warnings Warnings are notes that caution the student about certain C++
features, programming techniques, or practices that can lead to
malfunctioning programs or lost data.
Case Studies Case studies that simulate real-world applications appear in
many chapters throughout the text. These case studies are de-
signed to highlight the major topics of the chapter in which they
appear.
Review Questions Each chapter presents a thorough and diverse set of review
and Exercises questions, such as fill-in-the-blank and short answer, that check
the student’s mastery of the basic material presented in the chap-
ter. These are followed by exercises requiring problem solving
and analysis, such as the Algorithm Workbench, Predict the Out-
put, and Find the Errors sections. Answers to the odd-numbered
review questions and review exercises can be downloaded from
the book’s Companion Web site at www.pearsonhighered.com/
gaddis.
Programming Each chapter offers a pool of programming exercises designed
Challenges to solidify the student’s knowledge of the topics currently being
studied. In most cases the assignments present real-world prob-
lems 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 Available for download from the book’s Companion Web site at
Development www.pearsonhighered.com/gaddis. This is an ongoing project
Project: that instructors can optionally assign to teams of students. It
Serendipity systematically develops a “real-world” software package: a
Booksellers 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 tech-
niques 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 For easy access, a quick reference guide to the C++ language is
Reference Guide printed on the last two pages of Appendix C in the book.
C++11 Throughout the text, new C++11 language features are
introduced. Look for the C++11 icon to find these new features.
11
11
xxiv Preface
Supplements
Student Online Resources
Many student resources are available for this book from the publisher. The following items
are available on the Gaddis Series Companion Web site at www.pearsonhighered.com/gaddis:
● The source code for each example program in the book
● Access to the book’s companion VideoNotes
● A full set of appendices, including answers to the Checkpoint questions and answers
to the odd-numbered review questions
● A collection of valuable Case Studies
● The complete Serendipity Booksellers Project
Integrated Development Environment (IDE) Resource Kits
Professors who adopt this text can order it for students with a kit containing five popular
C++ IDEs (Microsoft® Visual Studio Express Edition, Dev C++, NetBeans, Eclipse, and
CodeLite) and access to a Web site containing written and video tutorials for getting started
in each IDE. For ordering information, please contact your campus Pearson Education rep-
resentative or visit www.pearsonhighered.com/cs.
Online Practice and Assessment with MyProgrammingLab
MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of pro-
gramming. Through practice exercises and immediate, personalized feedback, MyProgram-
mingLab improves the programming competence of beginning students who often struggle
with the basic concepts and paradigms of popular high-level programming languages.
A self-study and homework tool, a MyProgrammingLab course consists of hundreds of
small practice exercises organized around the structure of this textbook. For students, the
system automatically detects errors in the logic and syntax of their code submissions and
offers targeted hints that enable students to figure out what went wrong—and why. For
instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the
code inputted by students for review.
MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the
makers of the CodeLab interactive programming exercise system. For a full demonstration,
to see feedback from instructors and students, or to get started using MyProgrammingLab
in your course, visit www.myprogramminglab.com.
Instructor Resources
The following supplements are available to 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
Another Random Document on
Scribd Without Any Related Topics
an honest living—if they could get it—but cannot because labor is
cheap, and there are too many waiting to perform it. Even now our
gaols are filled with society-made criminals, that education and
better circumstances might have rescued from a life of misery and
crime. Even now youth is stunted and starved, and men and women
pine away, racked with some terrible disease which thoughtless and
careless parents have transmitted to them.
Reformers abate not your enthusiasm, but work bravely on.
Through the world diffuse the glorious light of knowledge, let men
learn that all crime is a mistake, that effects always follow causes,
and that a good effect never follows from a bad cause in a nation
that is governed on the principles of truth and justice.
Remove poverty by sound advice to the poor and by strenuous
efforts to improve men's surroundings. Stay the drunkard in his
downward course, and assist unceasingly all social and political
progress. Popularity you may never attain; even praise for your
unselfish labor may be denied you while you live. But good work
must leave its influence in the world; and your children's children will
assuredly profit by it. For as Carlyle truly says: "Beautiful it is to see
and understand that no worth, or known or unknown, can die even
on this earth. The work an unknown good man has done is like a
hidden vein of water flowing underground, secretly making the
ground green. It flows and flows; it joins itself with other veins and
veinlets, and one day it will start forth as a visible perennial well."
*** END OF THE PROJECT GUTENBERG EBOOK NATURAL MAN ***
Updated editions will replace the previous one—the old editions will
be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.
START: FULL LICENSE
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the free
distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.
Section 1. General Terms of Use and
Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only be
used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E. Unless you have removed all references to Project Gutenberg:
1.E.1. The following sentence, with active links to, or other
immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the
United States and most other parts of the world at no
cost and with almost no restrictions whatsoever. You
may copy it, give it away or re-use it under the terms
of the Project Gutenberg License included with this
eBook or online at www.gutenberg.org. If you are not
located in the United States, you will have to check the
laws of the country where you are located before using
this eBook.
1.E.2. If an individual Project Gutenberg™ electronic work is derived
from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.
1.E.3. If an individual Project Gutenberg™ electronic work is posted
with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.
1.E.4. Do not unlink or detach or remove the full Project
Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute this
electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
1.E.7. Do not charge a fee for access to, viewing, displaying,
performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.
1.E.8. You may charge a reasonable fee for copies of or providing
access to or distributing Project Gutenberg™ electronic works
provided that:
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You provide a full refund of any money paid by a user who
notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.
• You provide, in accordance with paragraph 1.F.3, a full refund of
any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™
electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.
1.F.
1.F.1. Project Gutenberg volunteers and employees expend
considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.
1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for
the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.
1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you
discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
1.F.5. Some states do not allow disclaimers of certain implied
warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.
1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,
the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.
Section 2. Information about the Mission
of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.
Volunteers and financial support to provide volunteers with the
assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.
Section 3. Information about the Project
Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.
The Foundation’s business office is located at 809 North 1500 West,
Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.
The Foundation is committed to complying with the laws regulating
charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.
While we cannot and do not solicit contributions from states where
we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.
International donations are gratefully accepted, but we cannot make
any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Section 5. General Information About
Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
This website includes information about Project Gutenberg™,
including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookname.com

Starting out with C from control structures through objects Eighth Edition Tony Gaddis

  • 1.
    Starting out withC from control structures through objects Eighth Edition Tony Gaddis download https://ebookname.com/product/starting-out-with-c-from-control- structures-through-objects-eighth-edition-tony-gaddis/ Get Instant Ebook Downloads – Browse at https://ebookname.com
  • 2.
    Instant digital products(PDF, ePub, MOBI) available Download now and explore formats that suit you... Starting Out with Visual C 2012 3; global Edition Tony Gaddis https://ebookname.com/product/starting-out-with- visual-c-2012-3-global-edition-tony-gaddis/ Starting Out With Python 3rd Edition Tony Gaddis https://ebookname.com/product/starting-out-with-python-3rd- edition-tony-gaddis/ Starting Out With Visual Basic 2008 Update 4th Edition Edition Gaddis https://ebookname.com/product/starting-out-with-visual- basic-2008-update-4th-edition-edition-gaddis/ Tundra 1st Edition Peter D. Moore https://ebookname.com/product/tundra-1st-edition-peter-d-moore/
  • 3.
    Wittgenstein and theHuman Form of Life 1st Edition Oswald Hanfling https://ebookname.com/product/wittgenstein-and-the-human-form-of- life-1st-edition-oswald-hanfling/ Contemporary Debates in Philosophy of Biology Contemporary Debates in Philosophy 1st Edition Francisco J. Ayala https://ebookname.com/product/contemporary-debates-in-philosophy- of-biology-contemporary-debates-in-philosophy-1st-edition- francisco-j-ayala/ Evil Andrew P. Chignell https://ebookname.com/product/evil-andrew-p-chignell/ The Macroeconomics of Global Imbalances European and Asian Perspectives 1st Edition Marc Uzan https://ebookname.com/product/the-macroeconomics-of-global- imbalances-european-and-asian-perspectives-1st-edition-marc-uzan/ Worker Absenteeism and Sick Pay 1st Edition John Treble https://ebookname.com/product/worker-absenteeism-and-sick- pay-1st-edition-john-treble/
  • 4.
    Plant Breeding ReviewsVolume 20 1st Edition Jules Janick (Editor) https://ebookname.com/product/plant-breeding-reviews- volume-20-1st-edition-jules-janick-editor/
  • 6.
    C++ EIGHTH ED ITION STARTING OUT WITH C++ From Control Structures through Objects
  • 7.
  • 8.
    C++ EIGHTH ED ITION STARTING OUT WITH C++ From Control Structures through Objects Tony Gaddis Haywood Community College Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
  • 9.
    Credits and acknowledgmentsborrowed from other sources and reproduced, with permission, appear on the Credits page in the endmatter of this textbook. Copyright © 2015, 2012, 2009 Pearson Education, Inc., publishing as Addison-Wesley All rights reserved. Manufactured in the United States of America. This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458 or you may fax your request to 201 236-3290. Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps. Library of Congress Cataloging-in-Publication Data Gaddis, Tony. Starting out with C++ : from control structures through objects/Tony Gaddis.—Eighth edition. pages cm Includes bibliographical references and index. Online the following appendices are available at www.pearsonhighered.com/gaddis: Appendix D: Introduction to flowcharting; Appendix E: Using UML in class design; Appendix F: Namespaces; Appendix G: Writing managed C++ code for the .net framework; Appendix H: Passing command line arguments; Appendix I: Header file and library function reference; Appendix J: Binary numbers and bitwise operations; Appendix K: Multi-source file programs; Appendix L: Stream member functions for formatting; Appendix M: Introduction to Microsoft Visual C++ 2010 express edition; Appendix N: Answers to checkpoints; and Appendix O: Solutions to odd-numbered review questions. ISBN-13: 978-0-13-376939-5 ISBN-10: 0-13-376939-9 1. C++ (Computer program language) I. Title. II. Title: From control structures through objects. QA76.73.C153G33 2014b 005.13’3—dc23 2014000213 10 9 8 7 6 5 4 3 2 1 Editorial Director: Marcia Horton Acquisitions Editor: Matt Goldstein Program Manager: Kayla Smith-Tarbox Director of Marketing: Christy Lesko Marketing Coordinator: Kathryn Ferranti Marketing Assistant: Jon Bryant Senior Managing Editor: Scott Disanno Senior Project Manager: Marilyn Lloyd Operations Supervisor: Vincent Scelta Operations Specialist: Linda Sager Art Director, Cover: Jayne Conte Text Designer: Joyce Cosentino Wells Cover Designer: Bruce Kenselaar Manager, Visual Research: Karen Sanatar Permissions Supervisor: Michael Joyce Permission Administrator: Jenell Forschler Cover Image: Sergio37_120/Fotolia Media Project Manager: Renata Butera Full-Service Project Manager: Jogender Taneja Aptara®, Inc. Full-Service Vendor: Aptara®, Inc. Printer/Binder: Courier Kendallville Cover Printer: Lehigh-Phoenix Color/Hagerstown ISBN 13: 978-0-13-376939-5 ISBN 10: 0-13-376939-9
  • 10.
    v Contents at aGlance Preface xv CHAPTER 1 Introduction to Computers and Programming 1 CHAPTER 2 Introduction to C++ 27 CHAPTER 3 Expressions and Interactivity 83 CHAPTER 4 Making Decisions 149 CHAPTER 5 Loops and Files 227 CHAPTER 6 Functions 299 CHAPTER 7 Arrays 375 CHAPTER 8 Searching and Sorting Arrays 457 CHAPTER 9 Pointers 495 CHAPTER 10 Characters, C-Strings, and More About the string Class 547 CHAPTER 11 Structured Data 599 CHAPTER 12 Advanced File Operations 657 CHAPTER 13 Introduction to Classes 711 CHAPTER 14 More About Classes 811 CHAPTER 15 Inheritance, Polymorphism, and Virtual Functions 891 CHAPTER 16 Exceptions, Templates, and the Standard Template Library (STL) 971 CHAPTER 17 Linked Lists 1025 CHAPTER 18 Stacks and Queues 1063 CHAPTER 19 Recursion 1121 CHAPTER 20 Binary Trees 1155 Appendix A: Getting Started with Alice 1185 Appendix B: The ASCII Character Set 1211 Appendix C: Operator Precedence and Associativity 1213 Quick References 1215
  • 11.
    vi Contents ata Glance Index 1217 Credit 1237 Online The following appendices are available at www.pearsonhighered.com/gaddis. Appendix D: Introduction to Flowcharting Appendix E: Using UML in Class Design Appendix F: Namespaces Appendix G: Passing Command Line Arguments Appendix H: Header File and Library Function Reference Appendix I: Binary Numbers and Bitwise Operations Appendix J: Multi-Source File Programs Appendix K: Stream Member Functions for Formatting Appendix L: Answers to Checkpoints Appendix M: Solutions to Odd-Numbered Review Questions
  • 12.
    Preface xv CHAPTER 1Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What Is a Program Made of? 14 1.5 Input, Processing, and Output 17 1.6 The Programming Process 18 1.7 Procedural and Object-Oriented Programming 22 CHAPTER 2 Introduction to C++ 27 2.1 The Parts of a C++ Program 27 2.2 The cout Object 31 2.3 The #include Directive 36 2.4 Variables and Literals 37 2.5 Identifiers 41 2.6 Integer Data Types 42 2.7 The char Data Type 48 2.8 The C++ string Class 52 2.9 Floating-Point Data Types 54 2.10 The bool Data Type 57 2.11 Determining the Size of a Data Type 58 2.12 Variable Assignments and Initialization 59 2.13 Scope 61 2.14 Arithmetic Operators 61 2.15 Comments 69 2.16 Named Constants 71 2.17 Programming Style 73 vii Contents
  • 13.
    viii Contents CHAPTER 3Expressions and Interactivity 83 3.1 The cin Object 83 3.2 Mathematical Expressions 89 3.3 When You Mix Apples and Oranges: Type Conversion 98 3.4 Overflow and Underflow 100 3.5 Type Casting 101 3.6 Multiple Assignment and Combined Assignment 104 3.7 Formatting Output 108 3.8 Working with Characters and string Objects 118 3.9 More Mathematical Library Functions 124 3.10 Focus on Debugging: Hand Tracing a Program 130 3.11 Focus on Problem Solving: A Case Study 132 CHAPTER 4 Making Decisions 149 4.1 Relational Operators 149 4.2 The if Statement 154 4.3 Expanding the if Statement 162 4.4 The if/else Statement 166 4.5 Nested if Statements 169 4.6 The if/else if Statement 176 4.7 Flags 181 4.8 Logical Operators 182 4.9 Checking Numeric Ranges with Logical Operators 189 4.10 Menus 190 4.11 Focus on Software Engineering: Validating User Input 193 4.12 Comparing Characters and Strings 195 4.13 The Conditional Operator 199 4.14 The switch Statement 202 4.15 More About Blocks and Variable Scope 211 CHAPTER 5 Loops and Files 227 5.1 The Increment and Decrement Operators 227 5.2 Introduction to Loops: The while Loop 232 5.3 Using the while Loop for Input Validation 239 5.4 Counters 241 5.5 The do-while Loop 242 5.6 The for Loop 247 5.7 Keeping a Running Total 257 5.8 Sentinels 260 5.9 Focus on Software Engineering: Deciding Which Loop to Use 261 5.10 Nested Loops 262 5.11 Using Files for Data Storage 265 5.12 Optional Topics: Breaking and Continuing a Loop 284 CHAPTER 6 Functions 299 6.1 Focus on Software Engineering: Modular Programming 299 6.2 Defining and Calling Functions 300 6.3 Function Prototypes 309 6.4 Sending Data into a Function 311
  • 14.
    Contents ix 6.5 PassingData by Value 316 6.6 Focus on Software Engineering: Using Functions in a Menu-Driven Program 318 6.7 The return Statement 322 6.8 Returning a Value from a Function 324 6.9 Returning a Boolean Value 332 6.10 Local and Global Variables 334 6.11 Static Local Variables 342 6.12 Default Arguments 345 6.13 Using Reference Variables as Parameters 348 6.14 Overloading Functions 354 6.15 The exit() Function 358 6.16 Stubs and Drivers 361 CHAPTER 7 Arrays 375 7.1 Arrays Hold Multiple Values 375 7.2 Accessing Array Elements 377 7.3 No Bounds Checking in C++ 384 7.4 Array Initialization 387 7.5 The Range-Based for Loop 392 7.6 Processing Array Contents 396 7.7 Focus on Software Engineering: Using Parallel Arrays 404 7.8 Arrays as Function Arguments 407 7.9 Two-Dimensional Arrays 418 7.10 Arrays with Three or More Dimensions 425 7.11 Focus on Problem Solving and Program Design: A Case Study 427 7.12 If You Plan to Continue in Computer Science: Introduction to the STL vector 429 CHAPTER 8 Searching and Sorting Arrays 457 8.1 Focus on Software Engineering: Introduction to Search Algorithms 457 8.2 Focus on Problem Solving and Program Design: A Case Study 463 8.3 Focus on Software Engineering: Introduction to Sorting Algorithms 470 8.4 Focus on Problem Solving and Program Design: A Case Study 477 8.5 If You Plan to Continue in Computer Science: Sorting and Searching vectors 485 CHAPTER 9 Pointers 495 9.1 Getting the Address of a Variable 495 9.2 Pointer Variables 497 9.3 The Relationship Between Arrays and Pointers 504 9.4 Pointer Arithmetic 508 9.5 Initializing Pointers 510 9.6 Comparing Pointers 511 9.7 Pointers as Function Parameters 513 9.8 Focus on Software Engineering: Dynamic Memory Allocation 522 9.9 Focus on Software Engineering: Returning Pointers from Functions 526 9.10 Using Smart Pointers to Avoid Memory Leaks 533 9.11 Focus on Problem Solving and Program Design: A Case Study 536
  • 15.
    x Contents CHAPTER 10Characters, C-Strings, and More About the string Class 547 10.1 Character Testing 547 10.2 Character Case Conversion 551 10.3 C-Strings 554 10.4 Library Functions for Working with C-Strings 558 10.5 C-String/Numeric Conversion Functions 569 10.6 Focus on Software Engineering: Writing Your Own C-String-Handling Functions 575 10.7 More About the C++ string Class 581 10.8 Focus on Problem Solving and Program Design: A Case Study 590 CHAPTER 11 Structured Data 599 11.1 Abstract Data Types 599 11.2 Focus on Software Engineering: Combining Data into Structures 601 11.3 Accessing Structure Members 604 11.4 Initializing a Structure 608 11.5 Arrays of Structures 611 11.6 Focus on Software Engineering: Nested Structures 613 11.7 Structures as Function Arguments 617 11.8 Returning a Structure from a Function 620 11.9 Pointers to Structures 623 11.10 Focus on Software Engineering: When to Use ., When to Use ->, and When to Use * 626 11.11 Unions 628 11.12 Enumerated Data Types 632 CHAPTER 12 Advanced File Operations 657 12.1 File Operations 657 12.2 File Output Formatting 663 12.3 Passing File Stream Objects to Functions 665 12.4 More Detailed Error Testing 667 12.5 Member Functions for Reading and Writing Files 670 12.6 Focus on Software Engineering: Working with Multiple Files 678 12.7 Binary Files 680 12.8 Creating Records with Structures 685 12.9 Random-Access Files 689 12.10 Opening a File for Both Input and Output 697 CHAPTER 13 Introduction to Classes 711 13.1 Procedural and Object-Oriented Programming 711 13.2 Introduction to Classes 718 13.3 Defining an Instance of a Class 723 13.4 Why Have Private Members? 736 13.5 Focus on Software Engineering: Separating Class Specification from Implementation 737 13.6 Inline Member Functions 743 13.7 Constructors 746 13.8 Passing Arguments to Constructors 750
  • 16.
    Contents xi 13.9 Destructors758 13.10 Overloading Constructors 762 13.11 Private Member Functions 765 13.12 Arrays of Objects 767 13.13 Focus on Problem Solving and Program Design: An OOP Case Study 771 13.14 Focus on Object-Oriented Programming: Simulating Dice with Objects 778 13.15 Focus on Object-Oriented Programming: Creating an Abstract Array Data Type 782 13.16 Focus on Object-Oriented Design: The Unified Modeling Language (UML) 785 13.17 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 788 CHAPTER 14 More About Classes 811 14.1 Instance and Static Members 811 14.2 Friends of Classes 819 14.3 Memberwise Assignment 824 14.4 Copy Constructors 825 14.5 Operator Overloading 831 14.6 Object Conversion 858 14.7 Aggregation 860 14.8 Focus on Object-Oriented Design: Class Collaborations 865 14.9 Focus on Object-Oriented Programming: Simulating the Game of Cho-Han 869 CHAPTER 15 Inheritance, Polymorphism, and Virtual Functions 891 15.1 What Is Inheritance? 891 15.2 Protected Members and Class Access 900 15.3 Constructors and Destructors in Base and Derived Classes 906 15.4 Redefining Base Class Functions 918 15.5 Class Hierarchies 923 15.6 Polymorphism and Virtual Member Functions 929 15.7 Abstract Base Classes and Pure Virtual Functions 945 15.8 Multiple Inheritance 952 CHAPTER 16 Exceptions, Templates, and the Standard Template Library (STL) 971 16.1 Exceptions 971 16.2 Function Templates 990 16.3 Focus on Software Engineering: Where to Start When Defining Templates 996 16.4 Class Templates 996 16.5 Introduction to the Standard Template Library (STL) 1005 CHAPTER 17 Linked Lists 1025 17.1 Introduction to the Linked List ADT 1025 17.2 Linked List Operations 1027 17.3 A Linked List Template 1043 17.4 Variations of the Linked List 1055 17.5 The STL list Container 1056
  • 17.
    xii Contents CHAPTER 18Stacks and Queues 1063 18.1 Introduction to the Stack ADT 1063 18.2 Dynamic Stacks 1080 18.3 The STL stack Container 1091 18.4 Introduction to the Queue ADT 1093 18.5 Dynamic Queues 1105 18.6 The STL deque and queue Containers 1112 CHAPTER 19 Recursion 1121 19.1 Introduction to Recursion 1121 19.2 Solving Problems with Recursion 1125 19.3 Focus on Problem Solving and Program Design: The Recursive gcd Function 1133 19.4 Focus on Problem Solving and Program Design: Solving Recursively Defined Problems 1134 19.5 Focus on Problem Solving and Program Design: Recursive Linked List Operations 1135 19.6 Focus on Problem Solving and Program Design: A Recursive Binary Search Function 1139 19.7 The Towers of Hanoi 1141 19.8 Focus on Problem Solving and Program Design: The QuickSort Algorithm 1144 19.9 Exhaustive Algorithms 1148 19.10 Focus on Software Engineering: Recursion vs. Iteration 1151 CHAPTER 20 Binary Trees 1155 20.1 Definition and Applications of Binary Trees 1155 20.2 Binary Search Tree Operations 1158 20.3 Template Considerations for Binary Search Trees 1175 Appendix A: Getting Started with Alice 1185 Appendix B: The ASCII Character Set 1211 Appendix C: Operator Precedence and Associativity 1213 Quick References 1215 Index 1217 Credit 1237 Online The following appendices are available at www.pearsonhighered.com/gaddis. Appendix D: Introduction to Flowcharting Appendix E: Using UML in Class Design Appendix F: Namespaces Appendix G: Passing Command Line Arguments Appendix H: Header File and Library Function Reference Appendix I: Binary Numbers and Bitwise Operations Appendix J: Multi-Source File Programs Appendix K: Stream Member Functions for Formatting Appendix L: Answers to Checkpoints Appendix M: Solutions to Odd-Numbered Review Questions
  • 18.
    LOCATION OF VIDEONOTESIN THE TEXT Chapter 1 Introduction to Flowcharting, p. 20 Designing a Program with Pseudocode, p. 20 Designing the Account Balance Program, p. 25 Predicting the Result of Problem 33, p. 26 Chapter 2 Using cout, p. 31 Variabe Definitions, p. 37 Assignment Statements and Simple Math Expressions, p. 62 Solving the Restaurant Bill Problem, p. 80 Chapter 3 Reading Input with cin, p. 83 Formatting Numbers with setprecision, p. 111 Solving the Stadium Seating Problem, p. 142 Chapter 4 The if Statement, p. 154 The if/else statement, p. 166 The if/else if Statement, p. 176 Solving the Time Calculator Problem, p. 221 Chapter 5 The while Loop, p. 232 The for Loop, p. 247 Reading Data from a File, p. 274 Solving the Calories Burned Problem, p. 293 Chapter 6 Functions and Arguments, p. 311 Value-Returnlng Functions, p. 324 Solving the Markup Problem, p. 366 Chapter 7 Accessing Array Elements With a Loop, p. 380 Passing an Array to a Function, p. 407 Solving the Chips and Salsa Problem, p. 448 Chapter 8 The Binary Search, p. 460 The Selection Sort, p. 474 Solving the Charge Account Validation Modification Problem, p. 492 Chapter 9 Dynamically Allocating an Array, p. 523 Solving the Pointer Rewrite Problem, p. 545 Chapter 10 Writing a C-String-Handling Function, p. 575 More About the string Class, p. 581 Solving the Backward String Problem, p. 594 (continued on the next page)
  • 19.
    LOCATION OF VIDEONOTESIN THE TEXT (continued) Chapter 11 Creating a Structure, p. 601 Passing a Structure to a Function, p. 617 Solving the Weather Statistics Problem, p. 652 Chapter 12 Passing File Stream Objects to Functions, p. 665 Working with Multiple Files, p. 678 Solving the File Encryption Filter Problem, p. 708 Chapter 13 Writing a Class, p. 718 Defining an Instance of a Class, p. 723 Solving the Employee Class Problem, p. 802 Chapter 14 Operator Overloading, p. 831 Class Aggregation, p. 860 Solving the NumDays Problem, p. 885 Chapter 15 Redefining a Base Class Function in a Derived Class, p. 918 Polymorphism, p. 929 Solving the Employee and Production-Worker Classes Problem, p. 963 Chapter 16 Throwing an Exception, p. 972 Handling an Exception, p. 972 Writing a Function Template, p. 990 Storing Objects in a vector, p. 1010 Solving the Exception Project Problem, p. 1024 Chapter 17 Appending a Node to a Linked List, p. 1028 Inserting a Node in a Linked List, p. 1035 Deleting a Node from a Linked List, p. 1039 Solving the Member Insertion by Position Problem, p. 1061 Chapter 18 Storing Objects in an STL stack, p. 1091 Storing Objects in an STL queue, p. 1114 Solving the File Compare Problem, p. 1119 Chapter 19 Reducing a Problem with Recursion, p. 1126 Solving the Recursive Multiplication Problem, p. 1153 Chapter 20 Inserting a Node in a Binary Tree, p. 1160 Deleting a Node from a Binary Tree, p. 1166 Solving the Node Counter Problem, p. 1182
  • 20.
    Welcome to StartingOut with C++: From Control Structures through Objects, 8th edition. This book is intended for use in a two-semester C++ programming sequence, or an acceler- ated 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 intro- ductory programming course. This text is rich in example programs that are concise, practi- cal, 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 Eighth Edition C++11 is the latest standard version of the C++ language. In previous years, while the stan- dard was being developed, it was known as C++0x. In August 2011, it was approved by the International Standards Organization (ISO), and the name of the standard was officially changed to C++11. Most of the popular compilers now support the C++11 standard. The new C++11 standard was the primary motivation behind this edition. Although this edition introduces many of the new language features, a C++11 compiler is not strictly required to use the book. As you progress through the book, you will see C++11 icons in the margins, next to the new features that are introduced. Programs appearing in sections that are not marked with this icon will still compile using an older compiler. Here is a summary of the new C++11 topics that are introduced in this edition: ● The auto key word is introduced as a way to simplify complex variable definitions. The auto key word causes the compiler to infer a variable’s data type from its initial- ization value. ● The long long int and unsigned long long int data types, and the LL literal suffix are introduced. ● Chapter 5 shows how to pass a string object directly to a file stream object’s open member function, without the need to call the c_str() member function. (A discus- sion of the c_str()function still exists for anyone using a legacy compiler.) Preface xv
  • 21.
    xvi Preface ● Therange-based for loop is introduced in Chapter 7. This new looping mechanism automatically iterates over each element of an array, vector, or other collection, without the need of a counter variable or a subscript. ● Chapter 7 shows how a vector can be initialized with an initialization list. ● The nullptr key word is introduced as the standard way of representing a null pointer. ● Smart pointers are introduced in Chapter 9, with an example of dynamic memory allocation using unique_ptr. ● Chapter 10 discusses the new, overloaded to_string functions for converting numeric values to string objects. ● The string class’s new back() and front() member functions are included in Chapter 10’s overview of the string class. ● Strongly typed enums are discussed in Chapter 11. ● Chapter 13 shows how to use the smart pointer unique_ptr to dynamically allocate an object. ● Chapter 15 discusses the override key word and demonstrates how it can help prevent subtle overriding errors.The final key word is discussed as a way of preventing a virtual member function from being overridden. In addition to the C++11 topics, the following general improvements were made: ● Several new programming problems have been added to the text, and many of the existing programming problems have been modified to make them unique from previ- ous editions. ● The discussion of early, historic computers in Chapter 1 is expanded. ● The discussion of literal values in Chapter 2 is improved. ● The introduction of the char data type in Chapter 2 is reorganized to use character literals in variable assignments before using ASCII values in variable assignments. ● The discussion of random numbers in Chapter 3 is expanded and improved, with the addition of a new In the Spotlight section. ● A new Focus on Object-Oriented Programming section has been added to Chapter 13, showing how to write a class that simulates dice. ● A new Focus on Object-Oriented Programming section has been added to Chapter 14, showing an object-oriented program that simulates the game of Cho-Han. The program uses objects for the dealer, two players, and a pair of dice. 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.
  • 22.
    Preface xvii Chapter 8 Searchingand Sorting Arrays Chapter 9 Pointers Chapter 10 Characters, Strings, and the string Class Chapter 12 Advanced File Operations* Chapter 20 Binary Trees Chapters 2–7 Basic Language Elements 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 *A few subtopics in Chapter 12 require Chapters 9 and 11. Chapter 1 Introduction Figure P-1
  • 23.
    xviii Preface Chapter 1covers 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 Chap- ter 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 fun- damentals of programming, problem solving, and software design. The components of pro- grams, 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, vari- able declarations, constants, comments, program output, simple arithmetic operations, and C-strings. Programming style conventions are introduced and good programming style is modeled here, as it is throughout the text. An optional section explains the difference between ANSI standard and pre-standard C++ programs. Chapter 3: Expressions and Interactivity In this chapter the student learns to write programs that input and handle numeric, char- acter, and string data. The use of arithmetic operators and the creation of mathematical expressions are covered in greater detail, with emphasis on operator precedence. Debug- ging is introduced, with a section on hand tracing a program. Sections are also included on simple output formatting, on data type conversion and type casting, and on using library functions that work with numbers. Chapter 4: Making Decisions Here the student learns about relational operators, relational expressions and how to con- trol the flow of a program with the if, if/else, and if/else if statements. The condi- tional 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.
  • 24.
    Preface xix Chapter 5:Loops and Files This chapter covers repetition control structures. The while loop, do-while loop, and for loop are taught, along with common uses for these devices. Counters, accumulators, run- ning totals, sentinels, and other application-related topics are discussed. Sequential file I/O is also introduced. The student learns to read and write text files, and use loops to process the data in a file. Chapter 6: Functions In this chapter the student learns how and why to modularize programs, using both void and value returning functions. Argument passing is covered, with emphasis on when argu- ments 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 algo- rithms. There is also a section on sorting and searching STL vector objects. Chapter 9: Pointers This chapter explains how to use pointers. Pointers are compared to and contrasted with reference variables. Other topics include pointer arithmetic, initialization of pointers, rela- tional comparison of pointers, pointers and arrays, pointers and functions, dynamic mem- ory allocation, and more. Chapter 10: Characters, C-strings, and More About the string Class This chapter discusses various ways to process text at a detailed level. Library functions for testing and manipulating characters are introduced. C-strings are discussed, and the tech- nique of storing C-strings in char arrays is covered. An extensive discussion of the string class methods is also given. Chapter 11: Structured Data The student is introduced to abstract data types and taught how to create them using struc- tures, unions, and enumerated data types. Discussions and examples include using pointers to structures, passing structures to functions, and returning structures from functions.
  • 25.
    xx Preface 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 fun- damental 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 pres- ents 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 assign- ment, and copy constructors are discussed. The chapter also includes in-depth sections on operator overloading, object conversion, and object aggregation. There is also a section on class collaborations and the use of CRC cards. Chapter 15: Inheritance, Polymorphism, and Virtual Functions The study of classes continues in this chapter with the subjects of inheritance, polymor- phism, and virtual member functions. The topics covered include base and derived class con- structors and destructors, virtual member functions, base class pointers, static and dynamic binding, multiple inheritance, and class hierarchies. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL) The student learns to develop enhanced error trapping techniques using exceptions. Discus- sion 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
  • 26.
    Preface xxi denominator (GCD),performing a binary search, and sorting (QuickSort). The classic Tow- ers 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. The following appendices are available online at www.pearsonhighered.com/gaddis. Appendix D: Introduction to Flowcharting A brief introduction to flowcharting. This tutorial discusses sequence, selection, case, repeti- tion, 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: Passing Command Line Arguments Teaches the student how to write a C++ program that accepts arguments from the command line. This appendix will be useful to students working in a command line environment, such as Unix, Linux, or the Windows command prompt. Appendix H: Header File and Library Function Reference This appendix provides a reference for the C++ library functions and header files discussed in the book. Appendix I: Binary Numbers and Bitwise Operations A guide to the C++ bitwise operators, as well as a tutorial on the internal storage of integers.
  • 27.
    xxii Preface Appendix J: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 K: Stream Member Functions for Formatting Covers stream member functions for formatting such as setf. Appendix L: Answers to Checkpoints Students may test their own progress by comparing their answers to the checkpoint exer- cises against this appendix. The answers to all Checkpoints are included. Appendix M: Solutions to Odd-Numbered Review Questions Another tool that students can use to gauge their progress. Features of the Text Concept Each major section of the text starts with a concept statement. Statements This statement summarizes the ideas of the section. Example Programs The text has hundreds of complete example programs, each designed to highlight the topic currently being studied. In most cases, these are practical, real-world examples. Source code for these programs is provided so that students can run the programs themselves. Program Output After each example program there is a sample of its screen output. This immediately shows the student how the program should function. In the Spotlight Each of these sections provides a programming problem and a detailed, step-by-step analysis showing the student how to solve it. VideoNotes A series of online videos, developed specifically for this book, is available for viewing at www.pearsonhighered.com/gaddis. 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 can be downloaded from the book’s Companion Web site at www. pearsonhighered.com/gaddis. This allows students to check how well they have learned a new topic. Notes Notes appear at appropriate places throughout the text. They are short explanations of interesting or often misunderstood points relevant to the topic at hand.
  • 28.
    Preface xxiii Warnings Warningsare notes that caution the student about certain C++ features, programming techniques, or practices that can lead to malfunctioning programs or lost data. Case Studies Case studies that simulate real-world applications appear in many chapters throughout the text. These case studies are de- signed to highlight the major topics of the chapter in which they appear. Review Questions Each chapter presents a thorough and diverse set of review and Exercises questions, such as fill-in-the-blank and short answer, that check the student’s mastery of the basic material presented in the chap- ter. These are followed by exercises requiring problem solving and analysis, such as the Algorithm Workbench, Predict the Out- put, and Find the Errors sections. Answers to the odd-numbered review questions and review exercises can be downloaded from the book’s Companion Web site at www.pearsonhighered.com/ gaddis. Programming Each chapter offers a pool of programming exercises designed Challenges to solidify the student’s knowledge of the topics currently being studied. In most cases the assignments present real-world prob- lems 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 Available for download from the book’s Companion Web site at Development www.pearsonhighered.com/gaddis. This is an ongoing project Project: that instructors can optionally assign to teams of students. It Serendipity systematically develops a “real-world” software package: a Booksellers 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 tech- niques 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 For easy access, a quick reference guide to the C++ language is Reference Guide printed on the last two pages of Appendix C in the book. C++11 Throughout the text, new C++11 language features are introduced. Look for the C++11 icon to find these new features. 11 11
  • 29.
    xxiv Preface Supplements Student OnlineResources Many student resources are available for this book from the publisher. The following items are available on the Gaddis Series Companion Web site at www.pearsonhighered.com/gaddis: ● The source code for each example program in the book ● Access to the book’s companion VideoNotes ● A full set of appendices, including answers to the Checkpoint questions and answers to the odd-numbered review questions ● A collection of valuable Case Studies ● The complete Serendipity Booksellers Project Integrated Development Environment (IDE) Resource Kits Professors who adopt this text can order it for students with a kit containing five popular C++ IDEs (Microsoft® Visual Studio Express Edition, Dev C++, NetBeans, Eclipse, and CodeLite) and access to a Web site containing written and video tutorials for getting started in each IDE. For ordering information, please contact your campus Pearson Education rep- resentative or visit www.pearsonhighered.com/cs. Online Practice and Assessment with MyProgrammingLab MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of pro- gramming. Through practice exercises and immediate, personalized feedback, MyProgram- mingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages. A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice exercises organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong—and why. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review. MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the makers of the CodeLab interactive programming exercise system. For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com. Instructor Resources The following supplements are available to 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
  • 30.
    Another Random Documenton Scribd Without Any Related Topics
  • 31.
    an honest living—ifthey could get it—but cannot because labor is cheap, and there are too many waiting to perform it. Even now our gaols are filled with society-made criminals, that education and better circumstances might have rescued from a life of misery and crime. Even now youth is stunted and starved, and men and women pine away, racked with some terrible disease which thoughtless and careless parents have transmitted to them. Reformers abate not your enthusiasm, but work bravely on. Through the world diffuse the glorious light of knowledge, let men learn that all crime is a mistake, that effects always follow causes, and that a good effect never follows from a bad cause in a nation that is governed on the principles of truth and justice. Remove poverty by sound advice to the poor and by strenuous efforts to improve men's surroundings. Stay the drunkard in his downward course, and assist unceasingly all social and political progress. Popularity you may never attain; even praise for your unselfish labor may be denied you while you live. But good work must leave its influence in the world; and your children's children will assuredly profit by it. For as Carlyle truly says: "Beautiful it is to see and understand that no worth, or known or unknown, can die even on this earth. The work an unknown good man has done is like a hidden vein of water flowing underground, secretly making the ground green. It flows and flows; it joins itself with other veins and veinlets, and one day it will start forth as a visible perennial well."
  • 32.
    *** END OFTHE PROJECT GUTENBERG EBOOK NATURAL MAN *** Updated editions will replace the previous one—the old editions will be renamed. Creating the works from print editions not protected by U.S. copyright law means that no one owns a United States copyright in these works, so the Foundation (and you!) can copy and distribute it in the United States without permission and without paying copyright royalties. Special rules, set forth in the General Terms of Use part of this license, apply to copying and distributing Project Gutenberg™ electronic works to protect the PROJECT GUTENBERG™ concept and trademark. Project Gutenberg is a registered trademark, and may not be used if you charge for an eBook, except by following the terms of the trademark license, including paying royalties for use of the Project Gutenberg trademark. If you do not charge anything for copies of this eBook, complying with the trademark license is very easy. You may use this eBook for nearly any purpose such as creation of derivative works, reports, performances and research. Project Gutenberg eBooks may be modified and printed and given away—you may do practically ANYTHING in the United States with eBooks not protected by U.S. copyright law. Redistribution is subject to the trademark license, especially commercial redistribution. START: FULL LICENSE
  • 33.
    THE FULL PROJECTGUTENBERG LICENSE
  • 34.
    PLEASE READ THISBEFORE YOU DISTRIBUTE OR USE THIS WORK To protect the Project Gutenberg™ mission of promoting the free distribution of electronic works, by using or distributing this work (or any other work associated in any way with the phrase “Project Gutenberg”), you agree to comply with all the terms of the Full Project Gutenberg™ License available with this file or online at www.gutenberg.org/license. Section 1. General Terms of Use and Redistributing Project Gutenberg™ electronic works 1.A. By reading or using any part of this Project Gutenberg™ electronic work, you indicate that you have read, understand, agree to and accept all the terms of this license and intellectual property (trademark/copyright) agreement. If you do not agree to abide by all the terms of this agreement, you must cease using and return or destroy all copies of Project Gutenberg™ electronic works in your possession. If you paid a fee for obtaining a copy of or access to a Project Gutenberg™ electronic work and you do not agree to be bound by the terms of this agreement, you may obtain a refund from the person or entity to whom you paid the fee as set forth in paragraph 1.E.8. 1.B. “Project Gutenberg” is a registered trademark. It may only be used on or associated in any way with an electronic work by people who agree to be bound by the terms of this agreement. There are a few things that you can do with most Project Gutenberg™ electronic works even without complying with the full terms of this agreement. See paragraph 1.C below. There are a lot of things you can do with Project Gutenberg™ electronic works if you follow the terms of this agreement and help preserve free future access to Project Gutenberg™ electronic works. See paragraph 1.E below.
  • 35.
    1.C. The ProjectGutenberg Literary Archive Foundation (“the Foundation” or PGLAF), owns a compilation copyright in the collection of Project Gutenberg™ electronic works. Nearly all the individual works in the collection are in the public domain in the United States. If an individual work is unprotected by copyright law in the United States and you are located in the United States, we do not claim a right to prevent you from copying, distributing, performing, displaying or creating derivative works based on the work as long as all references to Project Gutenberg are removed. Of course, we hope that you will support the Project Gutenberg™ mission of promoting free access to electronic works by freely sharing Project Gutenberg™ works in compliance with the terms of this agreement for keeping the Project Gutenberg™ name associated with the work. You can easily comply with the terms of this agreement by keeping this work in the same format with its attached full Project Gutenberg™ License when you share it without charge with others. 1.D. The copyright laws of the place where you are located also govern what you can do with this work. Copyright laws in most countries are in a constant state of change. If you are outside the United States, check the laws of your country in addition to the terms of this agreement before downloading, copying, displaying, performing, distributing or creating derivative works based on this work or any other Project Gutenberg™ work. The Foundation makes no representations concerning the copyright status of any work in any country other than the United States. 1.E. Unless you have removed all references to Project Gutenberg: 1.E.1. The following sentence, with active links to, or other immediate access to, the full Project Gutenberg™ License must appear prominently whenever any copy of a Project Gutenberg™ work (any work on which the phrase “Project Gutenberg” appears, or with which the phrase “Project Gutenberg” is associated) is accessed, displayed, performed, viewed, copied or distributed:
  • 36.
    This eBook isfor the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. 1.E.2. If an individual Project Gutenberg™ electronic work is derived from texts not protected by U.S. copyright law (does not contain a notice indicating that it is posted with permission of the copyright holder), the work can be copied and distributed to anyone in the United States without paying any fees or charges. If you are redistributing or providing access to a work with the phrase “Project Gutenberg” associated with or appearing on the work, you must comply either with the requirements of paragraphs 1.E.1 through 1.E.7 or obtain permission for the use of the work and the Project Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9. 1.E.3. If an individual Project Gutenberg™ electronic work is posted with the permission of the copyright holder, your use and distribution must comply with both paragraphs 1.E.1 through 1.E.7 and any additional terms imposed by the copyright holder. Additional terms will be linked to the Project Gutenberg™ License for all works posted with the permission of the copyright holder found at the beginning of this work. 1.E.4. Do not unlink or detach or remove the full Project Gutenberg™ License terms from this work, or any files containing a part of this work or any other work associated with Project Gutenberg™. 1.E.5. Do not copy, display, perform, distribute or redistribute this electronic work, or any part of this electronic work, without
  • 37.
    prominently displaying thesentence set forth in paragraph 1.E.1 with active links or immediate access to the full terms of the Project Gutenberg™ License. 1.E.6. You may convert to and distribute this work in any binary, compressed, marked up, nonproprietary or proprietary form, including any word processing or hypertext form. However, if you provide access to or distribute copies of a Project Gutenberg™ work in a format other than “Plain Vanilla ASCII” or other format used in the official version posted on the official Project Gutenberg™ website (www.gutenberg.org), you must, at no additional cost, fee or expense to the user, provide a copy, a means of exporting a copy, or a means of obtaining a copy upon request, of the work in its original “Plain Vanilla ASCII” or other form. Any alternate format must include the full Project Gutenberg™ License as specified in paragraph 1.E.1. 1.E.7. Do not charge a fee for access to, viewing, displaying, performing, copying or distributing any Project Gutenberg™ works unless you comply with paragraph 1.E.8 or 1.E.9. 1.E.8. You may charge a reasonable fee for copies of or providing access to or distributing Project Gutenberg™ electronic works provided that: • You pay a royalty fee of 20% of the gross profits you derive from the use of Project Gutenberg™ works calculated using the method you already use to calculate your applicable taxes. The fee is owed to the owner of the Project Gutenberg™ trademark, but he has agreed to donate royalties under this paragraph to the Project Gutenberg Literary Archive Foundation. Royalty payments must be paid within 60 days following each date on which you prepare (or are legally required to prepare) your periodic tax returns. Royalty payments should be clearly marked as such and sent to the Project Gutenberg Literary Archive Foundation at the address specified in Section 4, “Information
  • 38.
    about donations tothe Project Gutenberg Literary Archive Foundation.” • You provide a full refund of any money paid by a user who notifies you in writing (or by e-mail) within 30 days of receipt that s/he does not agree to the terms of the full Project Gutenberg™ License. You must require such a user to return or destroy all copies of the works possessed in a physical medium and discontinue all use of and all access to other copies of Project Gutenberg™ works. • You provide, in accordance with paragraph 1.F.3, a full refund of any money paid for a work or a replacement copy, if a defect in the electronic work is discovered and reported to you within 90 days of receipt of the work. • You comply with all other terms of this agreement for free distribution of Project Gutenberg™ works. 1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™ electronic work or group of works on different terms than are set forth in this agreement, you must obtain permission in writing from the Project Gutenberg Literary Archive Foundation, the manager of the Project Gutenberg™ trademark. Contact the Foundation as set forth in Section 3 below. 1.F. 1.F.1. Project Gutenberg volunteers and employees expend considerable effort to identify, do copyright research on, transcribe and proofread works not protected by U.S. copyright law in creating the Project Gutenberg™ collection. Despite these efforts, Project Gutenberg™ electronic works, and the medium on which they may be stored, may contain “Defects,” such as, but not limited to, incomplete, inaccurate or corrupt data, transcription errors, a copyright or other intellectual property infringement, a defective or
  • 39.
    damaged disk orother medium, a computer virus, or computer codes that damage or cannot be read by your equipment. 1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the “Right of Replacement or Refund” described in paragraph 1.F.3, the Project Gutenberg Literary Archive Foundation, the owner of the Project Gutenberg™ trademark, and any other party distributing a Project Gutenberg™ electronic work under this agreement, disclaim all liability to you for damages, costs and expenses, including legal fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE. 1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a defect in this electronic work within 90 days of receiving it, you can receive a refund of the money (if any) you paid for it by sending a written explanation to the person you received the work from. If you received the work on a physical medium, you must return the medium with your written explanation. The person or entity that provided you with the defective work may elect to provide a replacement copy in lieu of a refund. If you received the work electronically, the person or entity providing it to you may choose to give you a second opportunity to receive the work electronically in lieu of a refund. If the second copy is also defective, you may demand a refund in writing without further opportunities to fix the problem. 1.F.4. Except for the limited right of replacement or refund set forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
  • 40.
    INCLUDING BUT NOTLIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE. 1.F.5. Some states do not allow disclaimers of certain implied warranties or the exclusion or limitation of certain types of damages. If any disclaimer or limitation set forth in this agreement violates the law of the state applicable to this agreement, the agreement shall be interpreted to make the maximum disclaimer or limitation permitted by the applicable state law. The invalidity or unenforceability of any provision of this agreement shall not void the remaining provisions. 1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the trademark owner, any agent or employee of the Foundation, anyone providing copies of Project Gutenberg™ electronic works in accordance with this agreement, and any volunteers associated with the production, promotion and distribution of Project Gutenberg™ electronic works, harmless from all liability, costs and expenses, including legal fees, that arise directly or indirectly from any of the following which you do or cause to occur: (a) distribution of this or any Project Gutenberg™ work, (b) alteration, modification, or additions or deletions to any Project Gutenberg™ work, and (c) any Defect you cause. Section 2. Information about the Mission of Project Gutenberg™ Project Gutenberg™ is synonymous with the free distribution of electronic works in formats readable by the widest variety of computers including obsolete, old, middle-aged and new computers. It exists because of the efforts of hundreds of volunteers and donations from people in all walks of life. Volunteers and financial support to provide volunteers with the assistance they need are critical to reaching Project Gutenberg™’s goals and ensuring that the Project Gutenberg™ collection will
  • 41.
    remain freely availablefor generations to come. In 2001, the Project Gutenberg Literary Archive Foundation was created to provide a secure and permanent future for Project Gutenberg™ and future generations. To learn more about the Project Gutenberg Literary Archive Foundation and how your efforts and donations can help, see Sections 3 and 4 and the Foundation information page at www.gutenberg.org. Section 3. Information about the Project Gutenberg Literary Archive Foundation The Project Gutenberg Literary Archive Foundation is a non-profit 501(c)(3) educational corporation organized under the laws of the state of Mississippi and granted tax exempt status by the Internal Revenue Service. The Foundation’s EIN or federal tax identification number is 64-6221541. Contributions to the Project Gutenberg Literary Archive Foundation are tax deductible to the full extent permitted by U.S. federal laws and your state’s laws. The Foundation’s business office is located at 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up to date contact information can be found at the Foundation’s website and official page at www.gutenberg.org/contact Section 4. Information about Donations to the Project Gutenberg Literary Archive Foundation Project Gutenberg™ depends upon and cannot survive without widespread public support and donations to carry out its mission of increasing the number of public domain and licensed works that can be freely distributed in machine-readable form accessible by the widest array of equipment including outdated equipment. Many
  • 42.
    small donations ($1to $5,000) are particularly important to maintaining tax exempt status with the IRS. The Foundation is committed to complying with the laws regulating charities and charitable donations in all 50 states of the United States. Compliance requirements are not uniform and it takes a considerable effort, much paperwork and many fees to meet and keep up with these requirements. We do not solicit donations in locations where we have not received written confirmation of compliance. To SEND DONATIONS or determine the status of compliance for any particular state visit www.gutenberg.org/donate. While we cannot and do not solicit contributions from states where we have not met the solicitation requirements, we know of no prohibition against accepting unsolicited donations from donors in such states who approach us with offers to donate. International donations are gratefully accepted, but we cannot make any statements concerning tax treatment of donations received from outside the United States. U.S. laws alone swamp our small staff. Please check the Project Gutenberg web pages for current donation methods and addresses. Donations are accepted in a number of other ways including checks, online payments and credit card donations. To donate, please visit: www.gutenberg.org/donate. Section 5. General Information About Project Gutenberg™ electronic works Professor Michael S. Hart was the originator of the Project Gutenberg™ concept of a library of electronic works that could be freely shared with anyone. For forty years, he produced and distributed Project Gutenberg™ eBooks with only a loose network of volunteer support.
  • 43.
    Project Gutenberg™ eBooksare often created from several printed editions, all of which are confirmed as not protected by copyright in the U.S. unless a copyright notice is included. Thus, we do not necessarily keep eBooks in compliance with any particular paper edition. Most people start at our website which has the main PG search facility: www.gutenberg.org. This website includes information about Project Gutenberg™, including how to make donations to the Project Gutenberg Literary Archive Foundation, how to help produce our new eBooks, and how to subscribe to our email newsletter to hear about new eBooks.
  • 44.
    Welcome to ourwebsite – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookname.com