problem solving - pearson he ukcatalogue.pearsoned.co.uk/preface/0321531345.pdf · and solutions to...
Post on 13-Apr-2020
6 Views
Preview:
TRANSCRIPT
PROBLEM SOLVING
SEVENTH EDITION
WITH
A01_SAVI1346_07_SB_FM.fm Page i Tuesday, January 15, 2008 10:45 AM
A01_SAVI1346_07_SB_FM.fm Page ii Tuesday, January 15, 2008 10:45 AM
PROBLEM SOLVING
WALTER SAVITCH
CONTRIBUTOR
KENRICK MOCK
SEVENTH EDITION
UNIVERSITY OF CALIFORNIA, SAN DIEGO
UNIVERSITY OF ALASKA, ANCHORAGE
WITH
Boston San Francisco NewYork London Toronto Sydney Tokyo Singapore Madrid
Mexico City Munich Paris Cape Town Hong Kong Montreal
A01_SAVI1346_07_SB_FM.fm Page iii Tuesday, January 15, 2008 10:45 AM
Executive Editor Michael HirschAcquisitions Editor Matt GoldsteinEditorial Assistant Sarah MilmoreSenior Production Supervisor Marilyn LloydMarketing Manager Christopher KellyProduction Services,
Composition and Art Nesbitt Graphics, Inc.Copy Editor, Proofreader, and
Indexer Rose KernanText Design Sandra RigneyCover Design Barbara AtkinsonMedia Producer Bethany TiddSenior Manufacturing Buyer Carol MelvilleCover Image
Stepping stones in pond, Japan
Digital Vision Ltd./Super StockPrinter Courier Westford
Access the latest information about Addison-Wesley Computing titles from our World Wide Web site: http://www.aw-bc/computing
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial caps or all caps.
The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications.
Library of Congress Cataloging-in-Publication Data
Savitch, Walter J., 1943- Problem solving with C++ / Walter Savitch. -- 7th ed. p. cm. ISBN 0-321-53134-5 1. C++ (Computer program language) I. Title. QA76.73.C153S29 2008 005.13'3--dc22 2007052559
Copyright
©
2009 by Pearson Education, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. For information on obtaining permission for use of material in this work, please submit a written request to Pearson Education, Inc., Rights and Contracts Department, 501 Boylston Street, Suite 900, Boston, MA 02116, fax your request to 617 671-3447, or contact http://www.pearsoned.com/legal/permissions.htm
ISBN 13: 9780321531346ISBN 10: 0-321-53134-51 2 3 4 5 6 7 8 9 10-CRW-11 10 09 08
A01_SAVI1346_07_SB_FM.fm Page iv Friday, January 18, 2008 11:18 AM
v
Preface
This book is meant to be used in a first course in programming and computerscience using the C++ language. It assumes no previous programming experi-ence and no mathematics beyond high school algebra.
If you have used the previous edition of this book, you should read thefollowing section that explains the changes to this seventh edition, and thenyou can skip the rest of this preface. If you are new to this book, the rest of thispreface will give you an overview of the book.
Changes to the Seventh Edition
This seventh edition presents the same programming philosophy as the sixthedition. All of the material from the sixth edition remains. Thirty new program-ming projects have been added, and the presentation has been reworked inseveral chapters. Additional material on the
map
class has been added and theprogram examples have been updated for greater compatibility with a majorityof compilers in use today. Moreover, thirty-nine videos that cover specific topicsand solutions to the Programming Projects have been added to the book’swebsite. These video notes walk students through the process of both problemsolving and coding to help reinforce key programming concepts. An iconappears in the margin of the book when a video is available regarding the topiccovered in the text. Finally, in response to instructors’ reviews of the previousedition, introductory material on inheritance has been moved from Chapter 6,“I/O Streams,” to Chapter 10, “Defining Classes.” However, if you are aninstructor already using the sixth edition, you can continue to teach your coursealmost without change.
Choose Your Own Ordering of Topics
Most introductory textbooks that use C++ have a very detailed agenda thatinstructors must follow to use the book in their courses. That is not true of thisbook. If you are an instructor, this book adapts to the way you teach, rather thanmaking you adapt to the book. You can easily change the order in whichchapters and sections are covered without loss of continuity. A dependencychart at the end of this preface gives an overview of the orders in which chaptersand sections may be covered, and each chapter has a “Prerequisites” section thatexplains what parts of the book need to be covered before each section in thatchapter. This allows instructors to easily rearrange the order in which chapters,or even sections, are covered.
A01_SAVI1346_07_SB_FM.fm Page v Tuesday, January 15, 2008 10:45 AM
vi
PREFACE
Although this book uses libraries and teaches students the importance oflibraries, it does not require any nonstandard libraries. This book uses onlylibraries that are provided with essentially all C++ implementations.
Allows either Late or Early Introduction of Classes
This book allows for flexible coverage of classes. You may cover classes eitherearly or late.
The default ordering of chapters begins by introducing students to thefundamental concepts of variable declarations, expression evaluation, controlstructures, procedural abstraction, function definition, arrays, and pointer manip-ulation. This gives the student a solid foundation in the most basic of program-ming concepts before tackling the more sophisticated concepts involved in object-oriented programming. The book covers these most basic of programmingconcepts in Chapters 2 through 9. In Chapter 6, file I/O streams are used to teachstudents how to use classes. Because stream I/O does require some use ofnamespaces and class libraries, some minimal coverage of how to use predefinednamespaces and some standard library I/O classes is integrated into the first fewchapters. In Chapter 10, students learn how to write their own classes.
Instructors who prefer to introduce classes earlier in the course can rear-range the order of chapters to suit their approach. This is discussed in the section“Flexibility in Topic Ordering” later in this preface. Essentially, instructors cancover Chapter 10, “Defining Classes,” immediately after Chapter 6.
The book uses a measured approach to teaching classes. It teaches studentsto write some very simple classes, then adds constructors, overloading simpleoperators, overloading the I/O operators, and so forth. This measured approachkeeps the student from being overwhelmed with a long list of complicatedconstructions and concepts. However, one goal of this book is to get students towrite realistic class definitions without spending time writing classes that areartificially simple. By the end of Chapter 11, students are writing essentially thesame kinds of classes that they will be writing when they finish the course.
Inheritance is covered briefly in Chapter 10 so that students become aware ofthe concept. However, this book does not teach students how to write their ownderived classes and use virtual functions until Chapter 15. Some instructors maychoose to leave that material for a second course. Other instructors will want tointegrate this inheritance coverage into their course. If desired, the material oninheritance may be moved later, since Chapters 16 through 18 do not requireinheritance.
Accessibility to Students
It is not enough for a book to present the right topics in the right order. It is noteven enough for it to be clear and correct when read by an instructor or otherexperienced programmer. The material needs to be presented in a way that isaccessible to beginning students. In this introductory textbook, I have endeav-ored to write in a way that students find clear and friendly. Reports from the
A01_SAVI1346_07_SB_FM.fm Page vi Tuesday, January 15, 2008 10:45 AM
PREFACE
vii
many students who have used the earlier editions of this book confirm that thisstyle makes the material clear and often even enjoyable to students.
ANSI/ISO C++ Standard
This edition is fully compatible with compilers that meet the latest ANSI/ISOC++ standard.
Advanced Topics
Many “advanced topics” are becoming part of a standard CS1 course. Even ifthey are not part of a course, it is good to have them available in the text asenrichment material. This book offers a number of advanced topics that canbe integrated into a course or left as enrichment topics. It gives thoroughcoverage of C++ templates, inheritance (including virtual functions), excep-tion handling, and the STL (Standard Template Library).
Summary Boxes
Each major point is summarized in a boxed section. These boxed sections arespread throughout each chapter.
Self-Test Exercises
Each chapter contains numerous Self-Test Exercises at strategic points. Com-plete answers for all the Self-Test Exercises are given at the end of each chapter.
Video Notes
The icon in the margin indicates when an online video is available that relatesto the current topic in the book.
Classroom Tested
Hundreds of thousands of students have used the first six editions of thisbook. Many of these students and many of their instructors have given mefeedback about what worked and what did not work for them. The vastmajority of the comments were extremely positive and indicated that studentsand teachers liked the book pretty much as it was, but suggestions for somechanges were made. All suggestions for changes were carefully considered.That valuable feedback was used to revise this edition so that it fits students’and instructors’ needs even better than the previous editions.
Flexibility in Topic Ordering
This book was written to allow instructors wide latitude in reordering thematerial. To illustrate this flexibility, we suggest two alternative ways to order
A01_SAVI1346_07_SB_FM.fm Page vii Tuesday, January 15, 2008 10:45 AM
viii
PREFACE
the topics. There is no loss of continuity when the book is read in either ofthese ways. To ensure this continuity when you rearrange material, you mayneed to move sections rather than entire chapters. However, only largesections in convenient locations are moved. To help customize a particularorder for any class’s needs, the end of this preface contains a dependencychart, and each chapter has a “Prerequisites” section that explains whatmaterial needs to be covered before each section in that chapter.
Reordering 1: Earlier Classes
To effectively design classes, a student needs some basic tools such as controlstructures and function definitions. This basic material is covered in Chapters1 through 6. After completing Chapter 6, students can begin to write their ownclasses. One possible reordering of chapters that allows for such early coverageof classes is the following:
Basics:
Chapters 1, 2, 3, 4, 5, and 6. This material covers all control struc-tures, function definitions, and basic file I/O. Chapter 3, which covers additional control structures, could be deferred if you wish to cover classes as early as possible.
Classes and namespaces:
Chapter 10, Sections 11.1 and 11.2 of Chapter 11, and Chapter 12. This material covers defining classes, friends, overloaded operators, and namespaces.
Arrays, strings and vectors:
Chapters 7 and 8.
Pointers and dynamic arrays:
Chapter 9.
Arrays in classes:
Sections 11.3 and 11.4 of Chapter 11.
Inheritance:
Chapter 15.
Recursion:
Chapter 14 (Alternately, recursion may be moved to later in the course.)
Pointers and linked lists:
Chapter 13.
Any subset of the following chapters may also be used:
Exception handling:
Chapter 16.
Templates:
Chapter 17.
Standard Template Library:
Chapter 18.
Reordering 2: Classes Slightly Later but Still Early
This version covers all control structures and the basic material on arraysbefore doing classes, but classes are covered later than the previous orderingand slightly earlier than the default ordering.
Basics:
Chapters 1, 2, 3, 4, 5, and 6. This material covers all control struc-tures, function definitions, and the basic file I/O.
A01_SAVI1346_07_SB_FM.fm Page viii Tuesday, January 15, 2008 10:45 AM
PREFACE
ix
Arrays and strings:
Chapter 7, Sections 8.1 and 8.2 of Chapter 8.
Classes and namespaces:
Chapter 10, Sections 11.1 and 11.2 of Chapter 11, and Chapter 12. This material covers defining classes, friends, overloaded operators, and namespaces.
Pointers and dynamic arrays:
Chapter 9.
Arrays in classes:
Sections 11.3 and 11.4 of Chapter 11.
Inheritance:
Chapter 15.
Recursion:
Chapter 14. (Alternately, recursion may be moved to later in the course.)
Vectors:
Chapter 8.3.
Pointers and linked lists:
Chapter 13.
Any subset of the following chapters may also be used:
Exception handling:
Chapter 16.
Templates:
Chapter 17.
Standard Template Library:
Chapter 18.
Support Material
There is support material available to all users of this book and additionalmaterial available only to qualified instructors.
Materials Available to All Users of this Book
■
Source Code from the book
■
PowerPoint slides
■
Video Notes
To access these materials, go to:
http://www.aw.com/cssupport
Resources Available to Qualified Instructors Only
Visit Addison-Wesley’s instructor resource center (http://www.aw.com/irc), con-tact your local AW sales representative, or send email to computing@aw.comfor information on how to access instructor supplements:
■
Instructor’s Resource Guide—including chapter-by-chapter teaching hints,quiz questions with solutions, and solutions to many programming projects
■
Test Bank and Test Generator
■
PowerPoint Lectures—including programs and art from the text
■
Lab Manual
■
Instructor access to Addison-Wesley’s
MyCodeMate
A01_SAVI1346_07_SB_FM.fm Page ix Tuesday, January 15, 2008 10:45 AM
x
PREFACE
Visual C++ Support
In addition to the already listed support material, this text is also availablewith supplementary Visual C++ materials:
■
Visual C++ 2008 Programming Companion (includes Microsoft’s VisualC++ Express compiler)
■
Visual C++ 2005 Programming Companion (includes Microsoft’s VisualC++ 2005 compiler)
Contact your local Addison-Wesley/Pearson representative, or send email tocomputing@aw.com for information on obtaining the book with Visual C++.
Additional Support Material
■
Addison-Wesley’s
C++ Backpack Reference Guide
is a quick reference toC++’s most frequently used keywords and libraries. It integrates all thespecifics of C++ in one handy place including syntax examples, keyworddescriptions, and programming tips. The
C++ Backpack Reference Guide
isoffered at a discount when packaged with a new copy of this text.
■
Addison-Wesley’s
MyCodeMate
is a book-specific Web resource that pro-vides tutorial help and evaluation of student programs.
A complimentarysubscription to
MyCodeMate
is offered when the access code is orderedin a package with a new copy of this text.
Subscriptions can also be pur-chased online. For more information, visit http://www.mycodemate.com.
For more information on these and other resources available with thebook, contact your local Addison-Wesley representative, or send email tocomputing@aw.com.
Acknowledgments
Numerous individuals and groups have provided me with suggestions,discussions, and other help in preparing this textbook. Much of the firstedition of this book was written while I was visiting the Computer ScienceDepartment at the University of Colorado in Boulder. The remainder of thewriting on the first edition and the work on subsequent editions was done inthe Computer Science and Engineering Department at the University ofCalifornia, San Diego (UCSD). I am grateful to these institutions for providinga conducive environment for teaching this material and writing this book.
I would like to thank reviewers of this edition. They are: Joseph Allen(Community College of Rhode Island), Noah Aydin (Kenyon College), AndrewHaas (University at Albany, SUNY), Huzefa Kagdi (Kent State University), GillieanLee (Lander University), Cynthia Martincic (Saint Vincent College), Jeff Roach(East Tennessee State University), Susanne Sherba (University of Colorado, Boul-der), Michal Sramka (Florida Atlantic University), James Stepleton (Stevens Insti-tute of Technology), and Jeffrey Watson (Walla Walla Community College).
A01_SAVI1346_07_SB_FM.fm Page x Tuesday, January 15, 2008 10:45 AM
PREFACE
xi
I extend a special thanks to all the individuals who have contributedcritiques or programming projects for this or earlier editions and drafts of thisbook. In alphabetical order they are: Claire Bono, Richard Borie, Andrew Burt,Edward Carr, Karla Chaveau, Wei Lian Chen, Joel Cohen, Doug Cosman,Charles Dowling, Scot Drysdale, Joe Faletti, Alex Feldman, Sheila Foster, PauloFranca, Len Garrett, Jerrold Grossman, Eitan M. Gurari, Dennis Heckman, BobHolloway, Nisar Hundewale, Matt Johnson, Bruce Johnston, Larry Johnson,Thomas Judson, Paul J. Kaiser, Michael Keenan, Brian R. King, Paul Kube,Barney MacCabe, Steve Mahaney, Michael Main, Walter A. Manrique, AnneMarchant, John Marsaglia, Nat Martin, Bob Matthews, Jesse Morehouse, EthanMunson, Donald Needham, Dung Nguyen, Joseph D. Oldham, JenniferPerkins, Carol Roberts, Ken Rockwood, John Russo, Amber Settle, NaomiShapiro, Scott Strong, David Teague, Jerry Weltman, John J. Westman, andLinda F. Wilson.
I extend a special thanks to the many instructors who used early editionsof this book. Their comments provided some of the most helpful reviewingthat the book received.
I thank all the individuals at Addison-Wesley who contributed so much tomaking this book possible: Marilyn Lloyd, Sarah Milmore, Chris Kelly, and myeditor, Matt Goldstein.
Finally, I thank Kenrick Mock who implemented the changes in thisedition. He had the almost impossible task of pleasing me, my editor, and hisown sensibilities, and he did a superb job of it.
Walter Savitch
Dependency Chart
The dependency chart on the next page shows possible orderings of chaptersand subsections. A line joining two boxes means that the upper box must becovered before the lower box. Any ordering that is consistent with this partialordering can be read without loss of continuity. If a box contains a sectionnumber or numbers, then the box refers only to those sections and not to theentire chapter.
A01_SAVI1346_07_SB_FM.fm Page xi Tuesday, January 15, 2008 10:45 AM
xii
PREFACE
Chapter 12Separate
Compilation &Namespaces
*Chapter 16ExceptionHandling
Chapter 11Classes 211.1–11.2
Chapter 77.4, Multi-
DimensionalArrays
Chapter 10Classes 1
Chapter 6I/O Streams
Chapter 5Functions 2
Chapter 4Functions 1
Chapter 2C++ Basics
Chapter 3More Flow of
Control
Chapter 7Arrays7.1–7.3
Chapter 8Strings and
Vectors
Chapter 1111.3 Classes
& Arrays
Chapter 1111.4 Classes& Dynamic
Arrays
Chapter 17Templates
Chapter 18STL
Chapter 13Pointers andLinked Lists
Chapter 15Inheritance
Chapter 9Pointers and
DynamicArrays
Chapter 14Recursion
Chapter 1Introduction
*Chapter 16 contains occasional references to derived classes, butthose references can be omitted
DISPLAY P.1 Dependency Chart
A01_SAVI1346_07_SB_FM.fm Page xii Tuesday, January 15, 2008 10:45 AM
xiii
Brief Contents
Table of Location of Video Notes
Inside front cover
Chapter 1
Introduction to Computers and C++ Programming
1
Chapter 2
C++ Basics
39
Chapter 3
More Flow of Control
111
Chapter 4
Procedural Abstraction and Functions That Return a Value
181
Chapter 5
Functions for All Subtasks
251
Chapter 6
I/O Streams as an Introduction to Objects and Classes
305
Chapter 7
Arrays
375
Chapter 8
Strings and Vectors
445
Chapter 9
Pointers and Dynamic Arrays
499
Chapter 10
Defining Classes
529
Chapter 11
Friends, Overloaded Operators, and Arrays in Classes
609
A01_SAVI1346_07_SB_FM.fm Page xiii Tuesday, January 15, 2008 10:45 AM
xiv
BRIEF CONTENTS
Chapter 12
Separate Compilation and Namespaces
695
Chapter 13
Pointers and Linked Lists
733
Chapter 14
Recursion
781
Chapter 15 Inheritance 825
Chapter 16 Exception Handling 881
Chapter 17 Templates 913
Chapter 18 Standard Template Library 943
Appendices1 C++ Keywords 9992 Precedence of Operators 10003 The ASCII Character Set 10024 Some Library Functions 10035 Inline Functions 10116 Overloading the Array Index
Square Brackets 10127 The this Pointer 10148 Overloading Operators as Member
Operators 1017
Index 1019
A01_SAVI1346_07_SB_FM.fm Page xiv Tuesday, January 15, 2008 10:45 AM
xv
Contents
TABLE OF LOCATION OF VIDEO NOTES
Inside front cover
Chapter 1
Introduction to Computers and C++ Programming
1
1.1
COMPUTER SYSTEMS
2
Hardware 2Software 7High-Level Languages 8Compilers 9History Note 12
1.2
PROGRAMMING AND PROBLEM-SOLVING
12
Algorithms 12Program Design 15Object-Oriented Programming 17The Software Life Cycle 17
1.3
INTRODUCTION TO C++
19
Origins of the C++ Language 19A Sample C++ Program 20
Pitfall:
Using the Wrong Slash in
\n
24
Programming Tip:
Input and Output Syntax 24Layout of a Simple C++ Program 24
Pitfall:
Putting a Space before the
include
File Name 26Compiling and Running a C++ Program 27
Programming Tip:
Getting Your Program to Run 27
1.4
TESTING AND DEBUGGING
30
Kinds of Program Errors 30
Pitfall:
Assuming Your Program Is Correct 31
A01_SAVI1346_07_SB_FM.fm Page xv Friday, January 18, 2008 11:18 AM
xvi CONTENTS
Chapter Summary 32
Answers to Self-Test Exercises 33
Programming Projects 36
Chapter 2 C++ Basics 39
2.1 VARIABLES AND ASSIGNMENTS 40Variables 40Names: Identifiers 42Variable Declarations 44Assignment Statements 45Pitfall: Uninitialized Variables 47Programming Tip: Use Meaningful Names 49
2.2 INPUT AND OUTPUT 50Output Using cout 50Include Directives and Namespaces 52Escape Sequences 53Programming Tip: End Each Program with a \n or endl 55Formatting for Numbers with a Decimal Point 55Input Using cin 56Designing Input and Output 58Programming Tip: Line Breaks in I/O 58
2.3 DATA TYPES AND EXPRESSIONS 60The Types int and double 60Other Number Types 62The Type char 63The Type bool 64Introduction to the Class string 65Type Compatibilities 66Arithmetic Operators and Expressions 69Pitfall: Whole Numbers in Division 71More Assignment Statements 73
2.4 SIMPLE FLOW OF CONTROL 74A Simple Branching Mechanism 74Pitfall: Strings of Inequalities 80Pitfall: Using = in place of == 81Compound Statements 82Simple Loop Mechanisms 84
A01_SAVI1346_07_SB_FM.fm Page xvi Tuesday, January 15, 2008 10:45 AM
CONTENTS xvii
Increment and Decrement Operators 87Programming Example: Charge Card Balance 89
Pitfall: Infinite Loops 90
2.5 PROGRAM STYLE 93Indenting 93Comments 94Naming Constants 96
Chapter Summary 98
Answers to Self-Test Exercises 99
Programming Projects 104
Chapter 3 More Flow of Control 111
3.1 USING BOOLEAN EXPRESSIONS 112Evaluating Boolean Expressions 112Pitfall: Boolean Expressions Convert to int Values 116Enumeration Types (Optional) 119
3.2 MULTIWAY BRANCHES 120Nested Statements 120Programming Tip: Use Braces in Nested Statements 121Multiway if-else Statements 123Programming Example: State Income Tax 125
The switch Statement 129Pitfall: Forgetting a break in a switch Statement 133Using switch Statements for Menus 134Blocks 134Pitfall: Inadvertent Local Variables 139
3.3 MORE ABOUT C++ LOOP STATEMENTS 140The while Statements Reviewed 141Increment and Decrement Operators Revisited 142The for Statement 145Pitfall: Extra Semicolon in a for Statement 150What Kind of Loop to Use 151Pitfall: Uninitialized Variables and Infinite Loops 153The break Statement 153Pitfall: The break Statement in Nested Loops 155
A01_SAVI1346_07_SB_FM.fm Page xvii Tuesday, January 15, 2008 10:45 AM
xviii CONTENTS
3.4 DESIGNING LOOPS 156Loops for Sums and Products 156Ending a Loop 157Nested Loops 161Debugging Loops 163
Chapter Summary 166
Answers to Self-Test Exercises 167
Programming Projects 173
Chapter 4 Procedural Abstraction and Functions That Return a Value 181
4.1 TOP-DOWN DESIGN 182
4.2 PREDEFINED FUNCTIONS 183Using Predefined Functions 183Type Casting 188Older Form of Type Casting 190Pitfall: Integer Division Drops the Fractional Part 191
4.3 PROGRAMMER-DEFINED FUNCTIONS 192Function Definitions 192Functions That Return a Boolean Value 196Alternate Form for Function Declarations 199Pitfall: Arguments in the Wrong Order 199Function Definition–Syntax Summary 201More About Placement of Function Definitions 202Programming Tip: Use Function Calls in Branching Statements 202
4.4 PROCEDURAL ABSTRACTION 204The Black Box Analogy 204Programming Tip: Choosing Formal Parameter Names 206Programming Tip: Nested Loops 208Case Study: Buying Pizza 211Programming Tip: Use Pseudocode 217
4.5 LOCAL VARIABLES 218The Small Program Analogy 218Programming Example: Experimental Pea Patch 220
Global Constants and Global Variables 221
A01_SAVI1346_07_SB_FM.fm Page xviii Tuesday, January 15, 2008 10:45 AM
CONTENTS xix
Call-by-Value Formal Parameters Are Local Variables 224Namespaces Revisited 226Programming Example: The Factorial Function 229
4.6 OVERLOADING FUNCTION NAMES 230Introduction to Overloading 231Programming Example: Revised Pizza-Buying Program 233
Automatic Type Conversion 236
Chapter Summary 239
Answers to Self-Test Exercises 239
Programming Projects 244
Chapter 5 Functions for All Subtasks 251
5.1 void FUNCTIONS 252Definitions of void Functions 252Programming Example: Converting Temperatures 255
return Statements in void Functions 255
5.2 CALL-BY-REFERENCE PARAMETERS 259A First View of Call-by-Reference 259Call-by-Reference in Detail 262Programming Example: The swap_values Function 266
Mixed Parameter Lists 268Programming Tip: What Kind of Parameter to Use 268Pitfall: Inadvertent Local Variables 270
5.3 USING PROCEDURAL ABSTRACTION 272Functions Calling Functions 273Preconditions and Postconditions 273Case Study: Supermarket Pricing 274
5.4 TESTING AND DEBUGGING FUNCTIONS 282Stubs and Drivers 282
5.5 GENERAL DEBUGGING TECHNIQUES 287Keep an Open Mind 287Check Common Errors 288Localize the Error 288The assert macro 291
A01_SAVI1346_07_SB_FM.fm Page xix Tuesday, January 15, 2008 10:45 AM
xx CONTENTS
Chapter Summary 292
Answers to Self-Test Exercises 293
Programming Projects 297
Chapter 6 I/O Streams as an Introduction to Objects and Classes 305
6.1 STREAMS AND BASIC FILE I/O 306Why Use Files for I/O? 307File I/O 308Introduction to Classes and Objects 312Programming Tip: Check Whether a File Was Opened Successfully 313Techniques for File I/O 316Appending to a File (Optional) 320File Names as Input (Optional) 320
6.2 TOOLS FOR STREAM I/O 323Formatting Output with Stream Functions 323Manipulators 328Streams as Arguments to Functions 332Programming Tip: Checking for the End of a File 332A Note on Namespaces 336Programming Example: Cleaning Up a File Format 337
6.3 CHARACTER I/O 338The Member Functions get and put 339The putback Member Function (Optional) 342Programming Example: Checking Input 343
Pitfall: Unexpected '\n' in Input 346The eof Member Function 349Programming Example: Editing a Text File 352
Predefined Character Functions 352Pitfall: toupper and tolower Return Values 355
Chapter Summary 357
Answers to Self-Test Exercises 359
Programming Projects 364
A01_SAVI1346_07_SB_FM.fm Page xx Tuesday, January 15, 2008 10:45 AM
CONTENTS xxi
Chapter 7 Arrays 375
7.1 INTRODUCTION TO ARRAYS 376Declaring and Referencing Arrays 376Programming Tip: Use for Loops with Arrays 378Pitfall: Array Indexes Always Start with Zero 378Programming Tip: Use a Defined Constant for the Size of an Array 378Arrays in Memory 380Pitfall: Array Index Out of Range 381Initializing Arrays 383
7.2 ARRAYS IN FUNCTIONS 385Indexed Variables as Function Arguments 385Entire Arrays as Function Arguments 388The const Parameter Modifier 391Pitfall: Inconsistent Use of const Parameters 393Functions That Return an Array 394Case Study: Production Graph 394
7.3 PROGRAMMING WITH ARRAYS 408Partially Filled Arrays 408Programming Tip: Do Not Skimp on Formal Parameters 411Programming Example: Searching an Array 412
Programming Example: Sorting an Array 414
7.4 MULTIDIMENSIONAL ARRAYS 419Multidimensional Array Basics 420Multidimensional Array Parameters 420Programming Example: Two-Dimensional Grading Program 422
Pitfall: Using Commas Between Array Indexes 427
Chapter Summary 427
Answers to Self-Test Exercises 428
Programming Projects 433
Chapter 8 Strings and Vectors 445
8.1 AN ARRAY TYPE FOR STRINGS 447C-String Values and C-String Variables 447Pitfall: Using = and == with C Strings 451
A01_SAVI1346_07_SB_FM.fm Page xxi Tuesday, January 15, 2008 10:45 AM
xxii CONTENTS
Other Functions in <cstring> 453C-String Input and Output 457C-String-to-Number Conversions and Robust Input 460
8.2 THE STANDARD string CLASS 465Introduction to the Standard Class string 465I/O with the Class string 468Programming Tip: More Versions of getline 472Pitfall: Mixing cin >> variable; and getline 472String Processing with the Class string 474Programming Example: Palindrome Testing 476
Converting between string Objects and C Strings 481
8.3 VECTORS 482Vector Basics 482Pitfall: Using Square Brackets Beyond the Vector Size 484Programming Tip: Vector Assignment Is Well Behaved 486Efficiency Issues 487
Chapter Summary 488
Answers to Self-Test Exercises 489
Programming Projects 491
Chapter 9 Pointers and Dynamic Arrays 499
9.1 POINTERS 500Pointer Variables 501Basic Memory Management 508Pitfall: Dangling Pointers 509Static Variables and Automatic Variables 510Programming Tip: Define Pointer Types 510
9.2 DYNAMIC ARRAYS 513Array Variables and Pointer Variables 513Creating and Using Dynamic Arrays 513Pointer Arithmetic (Optional) 519Multidimensional Dynamic Arrays (Optional) 521
Chapter Summary 523
Answers to Self-Test Exercises 523
Programming Projects 524
A01_SAVI1346_07_SB_FM.fm Page xxii Tuesday, January 15, 2008 10:45 AM
CONTENTS xxiii
Chapter 10 Defining Classes 529
10.1 STRUCTURES 530Structures for Diverse Data 530Pitfall: Forgetting a Semicolon in a Structure Definition 535Structures as Function Arguments 536Programming Tip: Use Hierarchical Structures 537Initializing Structures 539
10.2 CLASSES 542Defining Classes and Member Functions 542Public and Private Members 547Programming Tip: Make All Member Variables Private 555Programming Tip: Define Accessor and Mutator Functions 555Programming Tip: Use the Assignment Operator with Objects 557Programming Example: BankAccount Class—Version 1 557
Summary of Some Properties of Classes 562Constructors for Initialization 564Programming Tip: Always Include a Default Constructor 572Pitfall: Constructors with No Arguments 573
10.3 ABSTRACT DATA TYPES 575Classes to Produce Abstract Data Types 576Programming Example: Alternative Implementation of a Class 580
10.4 INTRODUCTION TO INHERITANCE 584Inheritance Among Stream Classes 585Programming Example: Another new_line Function 588
Default Arguments for Functions (Optional) 589Defining Derived Classes 591
Chapter Summary 594
Answers to Self-Test Exercises 595
Programming Projects 603
Chapter 11 Friends, Overloaded Operators, and Arrays in Classes 609
11.1 FRIEND FUNCTIONS 610Programming Example: An Equality Function 610
Friend Functions 614
A01_SAVI1346_07_SB_FM.fm Page xxiii Tuesday, January 15, 2008 10:45 AM
xxiv CONTENTS
Programming Tip: Define Both Accessor Functions and Friend Functions 616Programming Tip: Use Both Member and Nonmember Functions 618Programming Example: Money Class (Version 1) 618
Implementation of digit_to_int (Optional) 625Pitfall: Leading Zeros in Number Constants 626The const Parameter Modifier 628Pitfall: Inconsistent Use of const 630
11.2 OVERLOADING OPERATORS 633Overloading Operators 634Constructors for Automatic Type Conversion 638Overloading Unary Operators 640Overloading >> and << 640
11.3 ARRAYS AND CLASSES 651Arrays of Classes 651Arrays as Class Members 655Programming Example: A Class for a Partially Filled Array 656
11.4 CLASSES AND DYNAMIC ARRAYS 659Programming Example: A String Variable Class 659
Destructors 663Pitfall: Pointers as Call-by-Value Parameters 665Copy Constructors 667Overloading the Assignment Operator 672
Chapter Summary 675
Answers to Self-Test Exercises 676
Programming Projects 686
Chapter 12 Separate Compilation and Namespaces 695
12.1 SEPARATE COMPILATION 696ADTs Reviewed 697Case Study: DigitalTime—A Class Compiled Separately 698Using #ifndef 707Programming Tip: Defining Other Libraries 710
A01_SAVI1346_07_SB_FM.fm Page xxiv Tuesday, January 15, 2008 10:45 AM
CONTENTS xxv
12.2 NAMESPACES 712Namespaces and using Directives 712Creating a Namespace 714Qualifying Names 717A Subtle Point About Namespaces (Optional) 718Unnamed Namespaces 719Programming Tip: Choosing a Name for a Namespace 722Pitfall: Confusing the Global Namespace and the Unnamed Namespace 724
Chapter Summary 727
Answers to Self-Test Exercises 727
Programming Projects 729
Chapter 13 Pointers and Linked Lists 733
13.1 NODES AND LINKED LISTS 734Nodes 734Linked Lists 740Inserting a Node at the Head of a List 741Pitfall: Losing Nodes 744Searching a Linked List 745Pointers as Iterators 749Inserting and Removing Nodes Inside a List 749Pitfall: Using the Assignment Operator with Dynamic Data Structures 752Variations on Linked Lists 754Linked Lists of Classes 756
13.2 STACKS AND QUEUES 760Stacks 760Programming Example: A Stack Class 761
Queues 766Programming Example: A Queue Class 767
Chapter Summary 771
Answers to Self-Test Exercises 772
Programming Projects 775
A01_SAVI1346_07_SB_FM.fm Page xxv Tuesday, January 15, 2008 10:45 AM
xxvi CONTENTS
Chapter 14 Recursion 781
14.1 RECURSIVE FUNCTIONS FOR TASKS 783Case Study: Vertical Numbers 783A Closer Look at Recursion 790Pitfall: Infinite Recursion 791Stacks for Recursion 793Pitfall: Stack Overflow 794Recursion Versus Iteration 795
14.2 RECURSIVE FUNCTIONS FOR VALUES 796General Form for a Recursive Function That Returns a Value 796Programming Example: Another Powers Function 797
14.3 THINKING RECURSIVELY 801Recursive Design Techniques 801Case Study: Binary Search—An Example of Recursive Thinking 803Programming Example: A Recursive Member Function 810
Chapter Summary 815
Answers to Self-Test Exercises 815
Programming Projects 820
Chapter 15 Inheritance 825
15.1 INHERITANCE BASICS 826Derived Classes 827Constructors in Derived Classes 835Pitfall: Use of Private Member Variables from the Base Class 838Pitfall: Private Member Functions Are Effectively Not Inherited 840The protected Qualifier 840Redefinition of Member Functions 843Redefining Versus Overloading 847Access to a Redefined Base Function 848
15.2 INHERITANCE DETAILS 849Functions That Are Not Inherited 850Assignment Operators and Copy Constructors in Derived Classes 850Destructors in Derived Classes 851
A01_SAVI1346_07_SB_FM.fm Page xxvi Tuesday, January 15, 2008 10:45 AM
CONTENTS xxvii
15.3 POLYMORPHISM 853Late Binding 853Virtual Functions in C++ 854Virtual Functions and Extended Type Compatibility 860Pitfall: The Slicing Problem 864Pitfall: Not Using Virtual Member Functions 864Pitfall: Attempting to Compile Class Definitions Without Definitions for Every Virtual Member Function 865Programming Tip: Make Destructors Virtual 866
Chapter Summary 867
Answers to Self-Test Exercises 868
Programming Projects 872
Chapter 16 Exception Handling 881
16.1 EXCEPTION-HANDLING BASICS 883A Toy Example of Exception Handling 883Defining Your Own Exception Classes 892Multiple Throws and Catches 892Pitfall: Catch the More Specific Exception First 896Programming Tip: Exception Classes Can Be Trivial 897Throwing an Exception in a Function 898Exception Specification 898Pitfall: Exception Specification in Derived Classes 902
16.2 PROGRAMMING TECHNIQUES FOR EXCEPTION HANDLING 903When to Throw an Exception 903Pitfall: Uncaught Exceptions 905Pitfall: Nested try-catch Blocks 905Pitfall: Overuse of Exceptions 905Exception Class Hierarchies 906Testing for Available Memory 906Rethrowing an Exception 907
Chapter Summary 907
Answers to Self-Test Exercises 907
Programming Projects 909
A01_SAVI1346_07_SB_FM.fm Page xxvii Tuesday, January 15, 2008 10:45 AM
xxviii CONTENTS
Chapter 17 Templates 913
17.1 TEMPLATES FOR ALGORITHM ABSTRACTION 914Templates for Functions 915Pitfall: Compiler Complications 919Programming Example: A Generic Sorting Function 921
Programming Tip: How to Define Templates 925Pitfall: Using a Template with an Inappropriate Type 926
17.2 TEMPLATES FOR DATA ABSTRACTION 927Syntax for Class Templates 927Programming Example: An Array Class 930
Chapter Summary 936
Answers to Self-Test Exercises 936
Programming Projects 939
Chapter 18 Standard Template Library 943
18.1 ITERATORS 945using Declarations 945Iterator Basics 946Pitfall: Compiler Problems 951Kinds of Iterators 952Constant and Mutable Iterators 956Reverse Iterators 957Other Kinds of Iterators 959
18.2 CONTAINERS 960Sequential Containers 960Pitfall: Iterators and Removing Elements 965Programming Tip: Type Definitions in Containers 965Container Adapters stack and queue 966Associative Containers set and map 970Efficiency 976
18.3 GENERIC ALGORITHMS 977Running Times and Big-O Notation 978Container Access Running Times 982Nonmodifying Sequence Algorithms 983Container Modifying Algorithms 989
A01_SAVI1346_07_SB_FM.fm Page xxviii Tuesday, January 15, 2008 10:45 AM
CONTENTS xxix
Set Algorithms 989Sorting Algorithms 991
Chapter Summary 991
Answers to Self-Test Exercises 992
Programming Projects 994
APPENDICES1 C++ Keywords 999
2 Precedence of Operators 1000
3 The ASCII Character Set 1002
4 Some Library Functions 1003
5 Inline Functions 1011
6 Overloading the Array Index Square Brackets 1012
7 The this Pointer 1014
8 Overloading Operators as Member Operators 1017
INDEX 1019
A01_SAVI1346_07_SB_FM.fm Page xxix Tuesday, January 15, 2008 10:45 AM
A01_SAVI1346_07_SB_FM.fm Page xxx Wednesday, January 16, 2008 12:10 PM
top related