Problem solving with C++ [Ninth edition] 9780133591743, 1292018240, 9781292018249, 0133591743

Solving with C++ became the leading book for the CS1 in C++ course. Since then, the number of schools using the book has

267 53 21MB

English Pages xxx, 1058 pages: illustrations; 24 cm [1090] Year 2014;2015

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover......Page 1
Title......Page 5
Copyright......Page 6
Contents......Page 17
Chapter 1 Introduction to Computers and C++ Programming......Page 33
Hardware......Page 34
Software......Page 39
High-Level Languages......Page 40
Compilers......Page 41
Algorithms......Page 44
Program Design......Page 47
Object-Oriented Programming......Page 48
The Software Life Cycle......Page 49
Origins of the C++ Language......Page 50
A Sample C++ Program......Page 51
Programming Tip: Input and Output Syntax......Page 55
Layout of a Simple C++ Program......Page 56
Compiling and Running a C++ Program......Page 58
Programming Tip: Getting Your Program to Run......Page 59
1.4 Testing and Debugging......Page 61
Kinds of Program Errors......Page 62
Pitfall: Assuming Your Program Is Correct......Page 63
Chapter Summary......Page 64
Answers to Self-Test Exercises......Page 65
Practice Programs......Page 67
Programming Projects......Page 68
Chapter 2 C++ Basics......Page 71
Variables......Page 72
Names: Identifiers......Page 74
Variable Declarations......Page 76
Assignment Statements......Page 77
Pitfall: Uninitialized Variables......Page 79
Programming Tip: Use Meaningful Names......Page 81
Output Using cout......Page 82
Include Directives and Namespaces......Page 84
Escape Sequences......Page 85
Formatting for Numbers with a Decimal Point......Page 87
Input Using cin......Page 88
Programming Tip: Line Breaks in I/O......Page 90
The Types int and double......Page 92
Other Number Types......Page 94
C++11 Types......Page 95
The Type char......Page 96
Introduction to the Class string......Page 98
Type Compatibilities......Page 100
Arithmetic Operators and Expressions......Page 101
Pitfall: Whole Numbers in Division......Page 104
2.4 Simple Flow of Control......Page 106
A Simple Branching Mechanism......Page 107
Pitfall: Strings of Inequalities......Page 112
Pitfall: Using = in place of ==......Page 113
Compound Statements......Page 114
Simple Loop Mechanisms......Page 116
Increment and Decrement Operators......Page 119
Programming Example: Charge Card Balance......Page 121
Pitfall: Infinite Loops......Page 122
Comments......Page 125
Naming Constants......Page 127
Answers to Self-Test Exercises......Page 130
Practice Programs......Page 135
Programming Projects......Page 137
Chapter 3 More Flow of Control......Page 143
Evaluating Boolean Expressions......Page 144
Pitfall: Boolean Expressions Convert to int Values......Page 148
Enumeration Types (Optional)......Page 151
Nested Statements......Page 152
Programming Tip: Use Braces in Nested Statements......Page 153
Multiway if-else Statements......Page 155
Programming Example: State Income Tax......Page 157
The switch Statement......Page 160
Pitfall: Forgetting a break in a switch Statement......Page 164
Using switch Statements for Menus......Page 165
Blocks......Page 167
Pitfall: Inadvertent Local Variables......Page 170
The while Statements Reviewed......Page 171
Increment and Decrement Operators Revisited......Page 173
The for Statement......Page 176
Pitfall: Extra Semicolon in a for Statement......Page 181
What Kind of Loop to Use......Page 182
Pitfall: Uninitialized Variables and Infinite Loops......Page 184
Pitfall: The break Statement in Nested Loops......Page 186
Loops for Sums and Products......Page 187
Ending a Loop......Page 189
Nested Loops......Page 192
Debugging Loops......Page 194
Chapter Summary......Page 197
Answers to Self-Test Exercises......Page 198
Practice Programs......Page 204
Programming Projects......Page 206
Chapter 4 Procedural Abstraction and FunctionsThat Return a Value......Page 213
4.1 Top-Down Design......Page 214
Using Predefined Functions......Page 215
Random Number Generation......Page 220
Type Casting......Page 222
Pitfall: Integer Division Drops the Fractional Part......Page 224
Function Definitions......Page 225
Alternate Form for Function Declarations......Page 231
Pitfall: Arguments in the Wrong Order......Page 232
Function Definition–Syntax Summary......Page 233
More About Placement of Function Definitions......Page 234
Programming Tip: Use Function Calls in Branching Statements......Page 235
The Black-Box Analogy......Page 236
Programming Tip: Choosing Formal Parameter Names......Page 239
Programming Tip: Nested Loops......Page 240
Case Study: Buying Pizza......Page 243
Programming Tip: Use Pseudocode......Page 249
The Small Program Analogy......Page 250
Global Constants and Global Variables......Page 253
Call-by-Value Formal Parameters Are Local Variables......Page 256
Block Scope......Page 258
Namespaces Revisited......Page 259
Programming Example: The Factorial Function......Page 262
Introduction to Overloading......Page 264
Programming Example: Revised Pizza-Buying Program......Page 267
Automatic Type Conversion......Page 270
Answers to Self-Test Exercises......Page 272
Practice Programs......Page 277
Programming Projects......Page 279
Chapter 5 Functions for All Subtasks......Page 283
Definitions of void Functions......Page 284
return Statements in void Functions......Page 287
A First View of Call-by-Reference......Page 291
Call-by-Reference in Detail......Page 294
Programming Example: The swap_values Function......Page 299
Mixed Parameter Lists......Page 300
Programming Tip: What Kind of Parameter to Use......Page 301
Pitfall: Inadvertent Local Variables......Page 302
Functions Calling Functions......Page 305
Preconditions and Postconditions......Page 307
Case Study: Supermarket Pricing......Page 308
5.4 Testing and Debugging Functions......Page 313
Stubs and Drivers......Page 314
Check Common Errors......Page 319
Localize the Error......Page 320
The assert Macro......Page 322
Chapter Summary......Page 324
Answers to Self-Test Exercises......Page 325
Practice Programs......Page 328
Programming Projects......Page 331
Chapter 6 I/O Streams as an Introduction to Objects and Classes......Page 337
6.1 Streams and Basic File I/O......Page 338
Why Use Files for I/O?......Page 339
File I/O......Page 340
Introduction to Classes and Objects......Page 344
Programming Tip: Check Whether a File Was Opened Successfully......Page 346
Techniques for File I/O......Page 348
Appending to a File (Optional)......Page 352
File Names as Input (Optional)......Page 353
Formatting Output with Stream Functions......Page 355
Manipulators......Page 361
Programming Tip: Checking for the End of a File......Page 364
A Note on Namespaces......Page 367
Programming Example: Cleaning Up a File Format......Page 368
The Member Functions get and put......Page 370
The putback Member Function (Optional)......Page 374
Programming Example: Checking Input......Page 375
Pitfall: Unexpected '\n' in Input......Page 377
Programming Example: Another new_line Function......Page 379
Default Arguments for Functions (Optional)......Page 380
The eof Member Function......Page 385
Programming Example: Editing a Text File......Page 387
Predefined Character Functions......Page 388
Pitfall: toupper and to lower Return Values......Page 390
Chapter Summary......Page 392
Answers to Self-Test Exercises......Page 393
Practice Programs......Page 400
Programming Projects......Page 402
Chapter 7 Arrays......Page 409
Declaring and Referencing Arrays......Page 410
Programming Tip: Use a Defined Constant for the Size of an Array......Page 412
Arrays in Memory......Page 414
Pitfall: Array Index Out of Range......Page 415
Programming Tip: C++11 Range-Based for Statement......Page 418
Indexed Variables as Function Arguments......Page 421
Entire Arrays as Function Arguments......Page 423
The const Parameter Modifier......Page 426
Functions That Return an Array......Page 429
Case Study: Production Graph......Page 430
Partially Filled Arrays......Page 443
Programming Example: Searching an Array......Page 446
Programming Example: Sorting an Array......Page 449
Programming Example: Bubble Sort......Page 453
7.4 Multidimensional Arrays......Page 456
Multidimensional Array Basics......Page 457
Programming Example: Two-Dimensional Grading Program......Page 459
Pitfall: Using Commas Between Array Indexes......Page 463
Chapter Summary......Page 464
Answers to Self-Test Exercises......Page 465
Practice Programs......Page 469
Programming Projects......Page 471
Chapter 8 Strings and Vectors......Page 483
C-String Values and C-String Variables......Page 485
Pitfall: Using = and == with C Strings......Page 488
Other Functions in ......Page 490
Pitfall: Copying past the end of a C-string using strcpy......Page 493
C-String Input and Output......Page 496
C-String-to-Number Conversions and Robust Input......Page 498
Introduction to the Standard Class string......Page 504
I/O with the Class string......Page 507
Programming Tip: More Versions of getline......Page 510
Pitfall: Mixing cin >> variable; and getline......Page 511
String Processing with the Class string......Page 512
Programming Example: Palindrome Testing......Page 516
Converting Between string Objects and C Strings......Page 519
Converting Between Strings and Numbers......Page 520
Vector Basics......Page 521
Pitfall: Using Square Brackets Beyond the Vector Size......Page 524
Efficiency Issues......Page 525
Answers to Self-Test Exercises......Page 527
Practice Programs......Page 529
Programming Projects......Page 530
Chapter 9 Pointers and Dynamic Arrays......Page 539
9.1 Pointers......Page 540
Pointer Variables......Page 541
Basic Memory Management......Page 548
Pitfall: Dangling Pointers......Page 549
Programming Tip: Define Pointer Types......Page 550
Array Variables and Pointer Variables......Page 553
Creating and Using Dynamic Arrays......Page 554
Pointer Arithmetic (Optional)......Page 560
Multidimensional Dynamic Arrays (Optional)......Page 562
Answers to Self-Test Exercises......Page 564
Practice Programs......Page 565
Programming Projects......Page 566
Chapter 10 Defining Classes......Page 573
Structures for Diverse Data......Page 574
Pitfall: Forgetting a Semicolon in a Structure Definition......Page 579
Structures as Function Arguments......Page 580
Programming Tip: Use Hierarchical Structures......Page 581
Initializing Structures......Page 583
Defining Classes and Member Functions......Page 586
Public and Private Members......Page 591
Programming Tip: Define Accessor and Mutator Functions......Page 599
Programming Tip: Use the Assignment Operator with Objects......Page 601
Programming Example: BankAccount Class—Version 1......Page 602
Summary of Some Properties of Classes......Page 606
Constructors for Initialization......Page 608
Programming Tip: Always Include a Default Constructor......Page 616
Pitfall: Constructors with No Arguments......Page 617
Member Initializers and Constructor Delegation in C++11......Page 619
10.3 Abstract Data Types......Page 620
Classes to Produce Abstract Data Types......Page 621
Programming Example: Alternative Implementation of a Class......Page 625
10.4 Introduction to Inheritance......Page 630
Derived Classes......Page 631
Defining Derived Classes......Page 632
Chapter Summary......Page 636
Answers to Self-Test Exercises......Page 637
Practice Programs......Page 643
Programming Projects......Page 644
Chapter 11 Friends, Overloaded Operators, and Arrays in Classes......Page 651
Programming Example: An Equality Function......Page 652
Friend Functions......Page 656
Programming Tip: Define Both Accessor Functions and Friend Functions......Page 658
Programming Example: Money Class (Version 1)......Page 660
Implementation of digit_to_int (Optional)......Page 667
Pitfall: Leading Zeros in Number Constants......Page 668
The const Parameter Modifier......Page 670
Pitfall: Inconsistent Use of const......Page 671
11.2 Overloading Operators......Page 675
Overloading Operators......Page 676
Constructors for Automatic Type Conversion......Page 679
Overloading Unary Operators......Page 681
Overloading >> and
Recommend Papers

Problem solving with C++ [Ninth edition]
 9780133591743, 1292018240, 9781292018249, 0133591743

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

Problem Solving with C++

For these Global Editions, the editorial team at Pearson has collaborated with educators across the world to address a wide range of subjects and requirements, equipping students with the best possible learning tools. This Global Edition preserves the cutting-edge approach and pedagogy of the original, but also features alterations, customization, and adaptation from the North American version.

NINTH edition Savitch Mock

This is a special edition of an established title widely used by colleges and universities throughout the world. Pearson published this exclusive edition for the benefit of students outside the United States and Canada. If you purchased this book within the United States or Canada you should be aware that it has been imported without the approval of the Publisher or Author.

Global edition

Global edition

Global edition

 Problem Solving with C++  ninth edition

W   alter Savitch • Kendrick Mock

Pearson Global Edition

SAVITCH_1292018240_mech.indd 1

20/08/14 7:00 PM

Online Access Thank you for purchasing a new copy of Problem Solving with C++, Ninth Edition, Global Edition. Your textbook includes one year of prepaid access to the book’s Companion Website. This prepaid subscription provides you with full access to the following student support areas: • VideoNotes

• Source Code • Lecture Slides

• Lab Manual

Use a coin to scratch off the coating and reveal your student access code. Do not use a knife or other sharp object as it may damage the code. To access the Problem Solving with C++, Ninth Edition, Global Edition Companion Website for the first time, you will need to register online using a computer with an Internet connection and a web browser. The process takes just a couple of minutes and only needs to be completed once. 1. Go to www.pearsonglobaleditions.com/savitch 2. Click on Companion Website. 3. Click on the Register button. 4. On the registration page, enter your student access code* found beneath the scratch-off panel. Do not type the dashes. You can use lower- or uppercase. 5. Follow the on-screen instructions. If you need help at any time during the online registration process, simply click the Need Help? icon. 6. Once your personal Login Name and Password are confirmed, you can begin using the Problem Solving with C++, Ninth Edition, Global Edition Companion Website! To log in after you have registered: You only need to register for this Companion Website once. After that, you can log in any time at www.pearsonglobaleditions.com/savitch by providing your Login Name and Password when prompted. *Important: The access code can only be used once. This subscription is valid for one year upon activation and is not transferable. If this access code has already been revealed, it may no longer be valid.

SAVITCH_1292018240_ifc.indd 1

22/08/14 6:09 PM

Ninth Edition

Problem Solving

A01_SAVI8249_FM_pp01-30.indd 1

with

C++

18/09/14 4:00 PM

A01_SAVI8249_FM_pp01-30.indd 2

18/09/14 4:00 PM

Ninth Edition Global Edition

Problem Solving

with

C++

Walter Savitch University of California, San Diego

Contributor

Kenrick Mock University of Alaska, Anchorage

GLOBAL EDITION CONTRIBUTORS

Simon Msanjila Mzumbe University, Tanzania

Lupyana Muiche Mzumbe University, Tanzania

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

A01_SAVI8249_FM_pp01-30.indd 3

18/09/14 4:00 PM

Editorial Director: Marcia Horton Acquisitions Editor: Matt Goldstein Program Manager: Kayla Smith-Tarbox Editorial Assistant: Kelsey Loanes Marketing Coordinator: Kathryn Ferranti Production Director: Erin Gregg Managing Editor: Scott Disanno Head, Learning Asset Acquisitions, Global Edition: Laura Dent Acquisition Editor, Global Edition: Subhasree Patra Project Editor, Global Edition: Anuprova Dey Chowdhuri Senior Operations Supervisor: Vincent Scelta

Operations Specialist: Linda Sager Cover Designer: Shree Mohanambal Inbakumar, Lumina Datamatics Permissions Manager: Timothy Nicholls Image Permissions Manager: Karen Sanatar Media Producer: Renata Butera Media Project Manager: Wanda Rockwell Full-Service Vendor: Hardik Popli, Cenveo® Publisher Services Composition: Cenveo Publisher Services Printer/Binder: Courier Westford Cover Printer: Courier Westford

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsonglobaleditions.com © Pearson Education Limited 2015 The rights of Walter Savitch and Kendrick Mock to be identified as the authors of this work have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988. Authorized adaptation from the United States edition, entitled Problem Solving with C++, 9th edition, ISBN 978-0-13-359174-3, by Walter Savitch and Kendrick Mock, published by Pearson Education © 2015. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmittedin any form or by any means, electronic, mechanical, photocopying, recording or otherwise, withouteither the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, ­LondonEC1N 8TS. All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners. Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear below, or on ­appropriate page within text. Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose. All such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantability, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services. The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full within the software version specified. Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation. ISBN 10: 1292018240 ISBN 13: 978-1-29-201824-9 10 9 8 7 6 5 4 3 2 1 14 13 12 11 10 British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library Typeset in 10 GiovanniStd-Book by Cenveo Publishing Services Printed and bound by Courier Westford The publisher’s policy is to use paper manufactured from sustainable forests.

A01_SAVI8249_FM_pp01-30.indd 4

29/09/14 6:02 PM

Preface

This book is meant to be used in a first course in programming and computer science using the C++ language. It assumes no previous programming experience and no mathematics beyond high school algebra. If you have used the previous edition of this book, you should read the following section that explains the changes to this ninth edition and then you can skip the rest of this preface. If you are new to this book, the rest of this preface will give you an overview of the book.

Changes to the Ninth Edition This ninth edition presents the same programming philosophy as the eighth edition. All of the material from the eighth edition remains, but with the following enhancements: ■ End-of-chapter programs are now split into Practice Programs and Programming Projects. Practice Programs require a direct application of concepts presented in the chapter and solutions are usually short. Practice Programs are appropriate for laboratory exercises. Programming Projects require additional problem solving and solutions are generally longer than Practice Programs. Programming Projects are appropriate for homework problems. ■ Introduction to C++11 in the context of C++98. Examples of C++11 content includes new integer types, the auto type, raw string literals, strong enumerations, nullptr, ranged for loop, conversion between strings and integers, member initializers, and constructor delegation. ■ Additional material on sorting, secure programming (e.g., overflow, array out of bounds), and inheritance. ■ Correction of errata. ■ Twenty-one new Practice Programs and ten new Programming Projects. ■ Ten new VideoNotes for a total of sixty-four VideoNotes. These VideoNotes walk students through the process of both problem solving and coding to help reinforce key programming concepts. An icon appears in the margin of the book when a VideoNote is available regarding the topic covered in the text. If you are an instructor already using the eighth edition, you can continue to teach your course almost without change.

Flexibility in Topic Ordering This book was written to allow instructors wide latitude in reordering the material. To illustrate this flexibility, we suggest two alternative ways to order

A01_SAVI8249_FM_pp01-30.indd 5

5

18/09/14 4:00 PM

6

Preface

the topics. There is no loss of continuity when the book is read in either of these ways. To ensure this continuity when you rearrange material, you may need to move sections rather than entire chapters. However, only large sections in convenient locations are moved. To help customize a particular order for any class’s needs, the end of this preface contains a dependency chart, and each chapter has a “Prerequisites” section that explains what material 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 control structures and function definitions. This basic material is covered in Chapters 1 through 6. After completing Chapter 6, students can begin to write their own classes. One possible reordering of chapters that allows for such early coverage of classes is the following: Basics: Chapters 1, 2, 3, 4, 5, and 6. This material covers all control structures, 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 arrays before doing classes, but classes are covered later than the previous ordering and slightly earlier than the default ordering. Basics: Chapters 1, 2, 3, 4, 5, and 6. This material covers all control structures, function definitions, and the basic file I/O.

A01_SAVI8249_FM_pp01-30.indd 6

18/09/14 4:00 PM



Preface

7

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

Accessibility to Students It is not enough for a book to present the right topics in the right order. It is not even enough for it to be clear and correct when read by an instructor or other experienced programmer. The material needs to be presented in a way that is accessible to beginning students. In this introductory textbook, I have endeavored to write in a way that students find clear and friendly. Reports from the many students who have used the earlier editions of this book confirm that this style 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/ISO C++ standard. At the time of this writing the latest standard is C++11.

Advanced Topics Many “advanced topics” are becoming part of a standard CS1 course. Even if they are not part of a course, it is good to have them available in the text as enrichment material. This book offers a number of advanced topics that can be integrated into a course or left as enrichment topics. It gives thorough coverage of C++ templates, inheritance (including virtual functions), exception handling, and the STL (Standard Template Library). Although this book uses libraries and teaches students the importance of libraries, it does not require any nonstandard libraries. This book uses only libraries that are provided with essentially all C++ implementations.

A01_SAVI8249_FM_pp01-30.indd 7

18/09/14 4:00 PM

8

Preface

Dependency Chart The dependency chart on the next page shows possible orderings of chapters and subsections. A line joining two boxes means that the upper box must be covered before the lower box. Any ordering that is consistent with this partial ordering can be read without loss of continuity. If a box contains a section number or numbers, then the box refers only to those sections and not to the entire chapter.

Summary Boxes Each major point is summarized in a boxed section. These boxed sections are spread throughout each chapter.

Self-Test Exercises Each chapter contains numerous Self-Test Exercises at strategic points. Complete answers for all the Self-Test Exercises are given at the end of each chapter.

VideoNotes VideoNote

A01_SAVI8249_FM_pp01-30.indd 8

VideoNotes are designed for teaching students key programming concepts and techniques. These short step-by-step videos demonstrate how to solve ­problems from design through coding. VideoNotes ­allow for self-paced ­instruction with easy navigation including the ability to select, play, rewind, fast-forward, and stop within each VideoNote exercise.

18/09/14 4:00 PM



9

Preface

DISPLAY P.1   Dependency Chart Chapter 1 Introduction

Chapter 2 C++ Basics

Chapter 4 Functions 1

Chapter 5 Functions 2

Chapter 3 More Flow of Control

Chapter 7 Arrays 7.1–7.3

Chapter 6 I/O Streams

Chapter 14 Recursion

Chapter 10 Classes 1

Chapter 7 7.4 MultiDimensional Arrays

Chapter 11 Classes 2 11.1–11.2

Chapter 8 Strings and Vectors

*Chapter 16 Exception Handling

Chapter 12 Separate ­Compilation & Namespaces

Chapter 11 11.3 Classes & Arrays

Chapter 9 Pointers and Dynamic Arrays

Chapter 11 11.4 Classes & Dynamic Arrays

Chapter 13 Pointers and Linked Lists

Chapter 15 Inheritance Chapter 17 Templates

*Chapter 16 contains occasional references to derived classes, but those references can be omitted

A01_SAVI8249_FM_pp01-30.indd 9

Chapter 18 STL

18/09/14 4:00 PM

10

Preface

Support Material There is support material available to all users of this book and additional material available only to qualified instructors. Materials Available to All Users of this Book ■ Source

Code from the book ■ PowerPoint slides ■ VideoNotes To access these materials, go to: www.pearsonglobaleditions.com/savitch Resources Available to Qualified Instructors Only Visit Pearson Education’s instructor resource center at www.pearsonglobal editions.com/savitch to access the following instructor resources: ■ 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

Integrated Development Environment (IDE) Resource Kits Instructors who adopt this text can order it for students with a kit containing five popular C++ IDEs (Microsoft® Visual Studio 2013 Express Edition, Dev C++, NetBeans, Eclipse, and CodeLite) and access to a Web site containing written and video tutorials for getting started in each IDE. For ordering information, please contact your campus Pearson Education representative.

Contact Us Your comments, suggestions, questions, and corrections are always welcome. Please e-mail them to [email protected]

Acknowledgments Numerous individuals and groups have provided me with suggestions, discussions, and other help in preparing this textbook. Much of the first edition of this book was written while I was visiting the Computer Science Department at the University of Colorado in Boulder. The remainder of the writing on the first edition and the work on subsequent editions was done in the Computer Science and Engineering Department at the University of California, San Diego (UCSD). I am grateful to these institutions for providing a conducive environment for teaching this material and writing this book.

A01_SAVI8249_FM_pp01-30.indd 10

18/09/14 4:00 PM



Preface

11

I extend a special thanks to all the individuals who have contributed critiques or programming projects for this or earlier editions and drafts of this book. In alphabetical order, they are: Alex Feldman, Amber Settle, Andrew Burt, Andrew Haas, Anne Marchant, Barney MacCabe, Bob Holloway, Bob Matthews, Brian R. King, Bruce Johnston, Carol Roberts, Charles Dowling, Claire Bono, Cynthia Martincic, David Feinstein, David Teague, Dennis Heckman, Donald Needham, Doug Cosman, Dung Nguyen, Edward Carr, Eitan M. Gurari, Ethan Munson, Firooz Khosraviyani, Frank Moore, Gilliean Lee, Huzefa Kagdi, James Stepleton, Jeff Roach, Jeffrey Watson, Jennifer Perkins, Jerry Weltman, Joe Faletti, Joel Cohen, John J. Westman, John Marsaglia, John Russo, Joseph Allen, Joseph D. Oldham, Jerrold Grossman, Jesse Morehouse, Karla Chaveau, Ken Rockwood, Larry Johnson, Len Garrett, Linda F. Wilson, Mal Gunasekera, Marianne Lepp, Matt Johnson, Michael Keenan, Michael Main, Michal Sramka, Naomi Shapiro, Nat Martin, Noah Aydin, Nisar Hundewale, Paul J. Kaiser, Paul Kube, Paulo Franca, Richard Borie, Scot Drysdale, Scott Strong, Sheila Foster, Steve Mahaney, Susanne Sherba, Thomas Judson, Walter A. Manrique, Wei Lian Chen, and Wojciech Komornicki. I extend a special thanks to the many instructors who used early editions of this book. Their comments provided some of the most helpful reviewing that the book received. Finally, I thank Kenrick Mock who implemented the changes in this edition. He had the almost impossible task of pleasing me, my editor, and his own sensibilities, and he did a superb job of it. Walter Savitch Pearson Education would like to thank Rosanne Els, Mohit Tahiliani, and Ajith Kumar J. for reviewing the Global Edition.

A01_SAVI8249_FM_pp01-30.indd 11

18/09/14 4:00 PM

A01_SAVI8249_FM_pp01-30.indd 12

18/09/14 4:00 PM

Brief Contents

Chapter 1

Introduction to Computers and C++ Programming  31

Chapter 2

C++ Basics  69

Chapter 3

More Flow of Control  141

Chapter 4

Procedural Abstraction and Functions That Return a Value  211

Chapter 5

Functions for All Subtasks  281

Chapter 6

I/O Streams as an Introduction to Objects and Classes  335

Chapter 7

Arrays  407

Chapter 8

Strings and Vectors  481

Chapter 9

Pointers and Dynamic Arrays  537

Chapter 10 Defining Classes  571 Chapter 11 Friends, Overloaded Operators, and Arrays in Classes  649

13

A01_SAVI8249_FM_pp01-30.indd 13

18/09/14 4:00 PM

14

Brief Contents

Chapter 12 Separate Compilation and Namespaces  733 Chapter 13 Pointers and Linked Lists  769 Chapter 14 Recursion  819 Chapter 15 Inheritance  863 Chapter 16 Exception Handling  923 Chapter 17 Templates  955 Chapter 18 Standard Template Library  987 Appendices 1 2 3 4 5 6

C++ Keywords  1045 Precedence of Operators  1046 The ASCII Character Set  1048 Some Library Functions  1049 Inline Functions  1056 Overloading the Array Index Square Brackets  1057

7 The this Pointer  1059 8 Overloading Operators as Member Operators  1062

Index  1064 Credits  1085

A01_SAVI8249_FM_pp01-30.indd 14

18/09/14 4:00 PM

Contents

Chapter 1 Introduction to Computers and C++ Programming  31 1.1  Computer Systems  32

Hardware  32 Software  37 High-Level Languages  38 Compilers  39 History Note  42 1.2  Programming and Problem-Solving  42

Algorithms  42 Program Design  45 Object-Oriented Programming  46 The Software Life Cycle  47 1.3  Introduction to C++  48

Origins of the C++ Language  48 A Sample C++ Program  49 Pitfall: Using the Wrong Slash in \n  53 Programming Tip: Input and Output Syntax  53 Layout of a Simple C++ Program  54 Pitfall: Putting a Space Before the include File Name  56 Compiling and Running a C++ Program  56 Pitfall: Compiling a C++11 program  57 Programming Tip: Getting Your Program to Run  57 1.4  Testing and Debugging  59

Kinds of Program Errors  60 Pitfall: Assuming Your Program Is Correct  61

15

A01_SAVI8249_FM_pp01-30.indd 15

18/09/14 4:00 PM

16

Contents

Chapter Summary  62 Answers to Self-Test Exercises  63 Practice Programs 65 Programming Projects  66

Chapter 2 

C++ Basics  69

2.1  Variables and Assignments  70

Variables  70 Names: Identifiers  72 Variable Declarations  74 Assignment Statements  75 Pitfall: Uninitialized Variables  77 Programming Tip: Use Meaningful Names  79 2.2  Input and Output  80

Output Using cout  80 Include Directives and Namespaces  82 Escape Sequences  83 Programming Tip: End Each Program with a \n or endl  85 Formatting for Numbers with a Decimal Point  85 Input Using cin  86 Designing Input and Output  88 Programming Tip: Line Breaks in I/O  88 2.3  Data Types and Expressions  90

The Types int and double  90 Other Number Types  92 C++11 Types  93 The Type char  94 The Type bool  96 Introduction to the Class string  96 Type Compatibilities  98 Arithmetic Operators and Expressions  99 Pitfall: Whole Numbers in Division  102 More Assignment Statements  104 2.4  Simple Flow of Control  104

A Simple Branching Mechanism  105 Pitfall: Strings of Inequalities  110 Pitfall: Using = in place of ==  111 Compound Statements  112

A01_SAVI8249_FM_pp01-30.indd 16

18/09/14 4:00 PM



Contents

17

Simple Loop Mechanisms  114 Increment and Decrement Operators  117 Programming Example: Charge Card Balance  119 Pitfall: Infinite Loops  120 2.5  Program Style  123

Indenting  123 Comments  123 Naming Constants  125

Chapter Summary  128 Answers to Self-Test Exercises  128 Practice Programs 133 Programming Projects  135

Chapter 3 

More Flow of Control  141

3.1 Using Boolean Expressions  142

Evaluating Boolean Expressions  142 Pitfall: Boolean Expressions Convert to int Values  146 Enumeration Types (Optional)  149 3.2  Multiway Branches  150

Nested Statements  150 Programming Tip: Use Braces in Nested Statements  151 Multiway if-else Statements  153 Programming Example: State Income Tax  155 The switch Statement  158 Pitfall: Forgetting a break in a switch Statement  162 Using switch Statements for Menus  163 Blocks  165 Pitfall: Inadvertent Local Variables  168 3.3  More About C++ Loop Statements  169

The while Statements Reviewed  169 Increment and Decrement Operators Revisited  171 The for Statement  174 Pitfall: Extra Semicolon in a for Statement  179 What Kind of Loop to Use  180 Pitfall: Uninitialized Variables and Infinite Loops  182 The break Statement  183 Pitfall: The break Statement in Nested Loops  184

A01_SAVI8249_FM_pp01-30.indd 17

18/09/14 4:00 PM

18

Contents

3.4  Designing Loops  185

Loops for Sums and Products  185 Ending a Loop  187 Nested Loops  190 Debugging Loops  192

Chapter Summary  195 Answers to Self-Test Exercises  196 Practice Programs 202 Programming Projects  204

Chapter 4 Procedural Abstraction and Functions That Return a Value  211 4.1  Top-Down Design  212 4.2  Predefined Functions  213

Using Predefined Functions  213 Random Number Generation  218 Type Casting  220 Older Form of Type Casting  222 Pitfall: Integer Division Drops the Fractional Part  222 4.3  Programmer-Defined Functions  223

Function Definitions  223 Functions That Return a Boolean Value  229 Alternate Form for Function Declarations  229 Pitfall: Arguments in the Wrong Order  230 Function Definition–Syntax Summary  231 More About Placement of Function Definitions  232 Programming Tip: Use Function Calls in Branching Statements  233 4.4  Procedural Abstraction  234

The Black-Box Analogy  234 Programming Tip: Choosing Formal Parameter Names  237 Programming Tip: Nested Loops  238 Case Study: Buying Pizza  241 Programming Tip: Use Pseudocode  247 4.5  Scope and Local Variables  248

The Small Program Analogy  248 Programming Example: Experimental Pea Patch  251

A01_SAVI8249_FM_pp01-30.indd 18

18/09/14 4:00 PM



Contents

19

Global Constants and Global Variables  251 Call-by-Value Formal Parameters Are Local Variables  254 Block Scope  256 Namespaces Revisited  257 Programming Example: The Factorial Function  260 4.6  Overloading Function Names  262

Introduction to Overloading  262 Programming Example: Revised Pizza-Buying Program  265 Automatic Type Conversion  268

Chapter Summary  270 Answers to Self-Test Exercises  270 Practice Programs 275 Programming Projects  277

Chapter 5 

Functions for All Subtasks  281

5.1  void Functions  282

Definitions of void Functions  282 Programming Example: Converting Temperatures  285 return Statements in void Functions  285

5.2  Call-By-Reference Parameters  289

A First View of Call-by-Reference  289 Call-by-Reference in Detail  292 Programming Example: The swap_values Function  297 Mixed Parameter Lists  298 Programming Tip: What Kind of Parameter to Use  299 Pitfall: Inadvertent Local Variables  300 5.3 Using Procedural Abstraction  303

Functions Calling Functions  303 Preconditions and Postconditions  305 Case Study: Supermarket Pricing  306 5.4  Testing and Debugging Functions  311

Stubs and Drivers  312 5.5 General Debugging Techniques  317

Keep an Open Mind  317 Check Common Errors  317

A01_SAVI8249_FM_pp01-30.indd 19

18/09/14 4:00 PM

20

Contents

Localize the Error  318 The assert Macro  320

Chapter Summary  322 Answers to Self-Test Exercises  323 Practice Programs 326 Programming Projects  329

Chapter 6 I/O Streams as an Introduction to Objects and Classes  335 6.1  Streams and Basic File I/O  336

Why Use Files for I/O?  337 File I/O  338 Introduction to Classes and Objects  342 Programming Tip: Check Whether a File Was Opened Successfully  344 Techniques for File I/O  346 Appending to a File (Optional)  350 File Names as Input (Optional)  351 6.2  Tools for Stream I/O  353

Formatting Output with Stream Functions  353 Manipulators  359 Streams as Arguments to Functions  362 Programming Tip: Checking for the End of a File  362 A Note on Namespaces  365 Programming Example: Cleaning Up a File Format  366 6.3  Character I/O  368

The Member Functions get and put  368 The putback Member Function (Optional)  372 Programming Example: Checking Input  373 Pitfall: Unexpected '\n' in Input  375 Programming Example: Another new_line Function  377 Default Arguments for Functions (Optional)  378 The eof Member Function  383 Programming Example: Editing a Text File  385 Predefined Character Functions  386 Pitfall: toupper and tolower Return Values  388

A01_SAVI8249_FM_pp01-30.indd 20

18/09/14 4:00 PM



Contents

21

Chapter Summary  390 Answers to Self-Test Exercises  391 Practice Programs 398 Programming Projects  400

Chapter 7 

Arrays  407

7.1  Introduction to Arrays  408

Declaring and Referencing Arrays  408 Programming Tip: Use for Loops with Arrays  410 Pitfall: Array Indexes Always Start with Zero  410 Programming Tip: Use a Defined Constant for the Size of an Array  410 Arrays in Memory  412 Pitfall: Array Index Out of Range  413 Initializing Arrays  416 Programming Tip: C++11 Range-Based for Statement  416 7.2  Arrays in Functions  419

Indexed Variables as Function Arguments  419 Entire Arrays as Function Arguments  421 The const Parameter Modifier  424 Pitfall: Inconsistent Use of const Parameters  427 Functions That Return an Array  427 Case Study: Production Graph  428 7.3  Programming with Arrays  441

Partially Filled Arrays  441 Programming Tip: Do Not Skimp on Formal Parameters  444 Programming Example: Searching an Array  444 Programming Example: Sorting an Array  447 Programming Example: Bubble Sort  451 7.4  Multidimensional Arrays  454

Multidimensional Array Basics  455 Multidimensional Array Parameters  455 Programming Example: Two-Dimensional Grading Program  457 Pitfall: Using Commas Between Array Indexes  461

A01_SAVI8249_FM_pp01-30.indd 21

18/09/14 4:00 PM

22

Contents

Chapter Summary  462 Answers to Self-Test Exercises  463 Practice Programs 467 Programming Projects  469

Chapter 8 

Strings and Vectors  481

8.1  An Array Type for Strings  483

C-String Values and C-String Variables  483 Pitfall: Using = and == with C Strings  486 Other Functions in   488 Pitfall: Copying past the end of a C-string using strcpy  491 C-String Input and Output  494 C-String-to-Number Conversions and Robust Input  496 8.2  The Standard string Class  502

Introduction to the Standard Class string  502 I/O with the Class string  505 Programming Tip: More Versions of getline  508 Pitfall: Mixing cin >> variable; and getline  509 String Processing with the Class string  510 Programming Example: Palindrome Testing  514 Converting Between string Objects and C Strings  517 Converting Between Strings and Numbers  518 8.3  Vectors  519

Vector Basics  519 Pitfall: Using Square Brackets Beyond the Vector Size  522 Programming Tip: Vector Assignment Is Well Behaved  523 Efficiency Issues  523

Chapter Summary  525 Answers to Self-Test Exercises  525 Practice Programs 527 Programming Projects  528

Chapter 9 

Pointers and Dynamic Arrays  537

9.1  Pointers  538

Pointer Variables  539 Basic Memory Management  546

A01_SAVI8249_FM_pp01-30.indd 22

18/09/14 4:00 PM



Contents

23

Pitfall: Dangling Pointers  547 Static Variables and Automatic Variables  548 Programming Tip: Define Pointer Types  548 9.2  Dynamic Arrays  551

Array Variables and Pointer Variables  551 Creating and Using Dynamic Arrays  552 Pointer Arithmetic (Optional)  558 Multidimensional Dynamic Arrays (Optional)  560

Chapter Summary  562 Answers to Self-Test Exercises  562 Practice Programs 563 Programming Projects  564

Chapter 10 

Defining Classes  571

10.1  Structures  572

Structures for Diverse Data  572 Pitfall: Forgetting a Semicolon in a Structure Definition  577 Structures as Function Arguments  578 Programming Tip: Use Hierarchical Structures  579 Initializing Structures  581 10.2  Classes  584

Defining Classes and Member Functions  584 Public and Private Members  589 Programming Tip: Make All Member Variables Private  597 Programming Tip: Define Accessor and Mutator Functions  597 Programming Tip: Use the Assignment Operator with Objects  599 Programming Example: BankAccount Class—Version 1  600 Summary of Some Properties of Classes  604 Constructors for Initialization  606 Programming Tip: Always Include a Default Constructor  614 Pitfall: Constructors with No Arguments  615 Member Initializers and Constructor Delegation in C++11  617 10.3  Abstract Data Types  618

Classes to Produce Abstract Data Types  619 Programming Example: Alternative Implementation of a Class  623

A01_SAVI8249_FM_pp01-30.indd 23

18/09/14 4:00 PM

24

Contents

10.4  Introduction to Inheritance  628

Derived Classes  629 Defining Derived Classes  630

Chapter Summary  634 Answers to Self-Test Exercises  635 Practice Programs 641 Programming Projects  642

Chapter 11 Friends, Overloaded Operators, and Arrays in Classes  649 11.1  Friend Functions  650

Programming Example: An Equality Function  650 Friend Functions  654 Programming Tip: Define Both Accessor Functions and Friend Functions  656 Programming Tip: Use Both Member and Nonmember Functions  658 Programming Example: Money Class (Version 1)  658 Implementation of digit_to_int (Optional)  665 Pitfall: Leading Zeros in Number Constants  666 The const Parameter Modifier  668 Pitfall: Inconsistent Use of const  669 11.2  Overloading Operators  673

Overloading Operators  674 Constructors for Automatic Type Conversion  677 Overloading Unary Operators  679 Overloading >> and number) cout