A First Book of C++, Fourth Edition

  • 23 696 8
  • 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

This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. The publisher reserves the right to remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous editions, changes to current editions, and alternate formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for materials in your areas of interest.

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.

A First Book of

C++ Fourth Edition

Gary Bronson Fairleigh Dickenson University

Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States

A_C7785_FM.1c i

1/18/11 10:42 AM

A First Book of C++, Fourth Edition Gary Bronson Executive Editor: Marie Lee Acquisitions Editor: Brandi Shailer Senior Product Manager: Alyssa Pratt Development Editor: Lisa M. Lord Copyeditor: Michael Beckett Proofreader: Camille Kiolbasa Indexer: Michael Brackney Editorial Assistant: Jacqueline Lacaire Content Project Manager: Lisa Weidenfeld Associate Marketing Manager: Shanna Shelton Art Director: Faith Brosnan Print Buyer: Julio Esperas Cover Photo: ©istockphoto.com/xmanphoto

© 2012 Course Technology, Cengage Learning ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be reproduced, transmitted, stored or used in any form or by any means graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the publisher. For product information and technology assistance, contact us at Cengage Learning Customer & Sales Support, 1-800-354-9706 For permission to use material from this text or product, submit all requests online at www.cengage.com/permissions Further permissions questions can be emailed to [email protected]

Library of Congress Control Number: 2010939813 ISBN-13: 978-1-111-53100-3 ISBN-10: 1-111-53100-5

Compositor: GEX Publishing Services

Some of the product names and company names used in this book have been used for identification purposes only and may be trademarks or registered trademarks of their respective manufacturers and sellers. Any fictional data related to persons or companies or URLs used throughout this book is intended for instructional purposes only. At the time this book was printed, any such data was fictional and not belonging to any real persons or companies. Course Technology, a part of Cengage Learning, reserves the right to revise this publication and make changes from time to time in its content without notice. The programs in this book are for instructional purposes only.

Course Technology 20 Channel Center Street Boston, MA 02210 USA They have been tested with care, but are not guaranteed for any particular intent beyond educational purposes. The author and the publisher do not offer any warranties or representations, nor do they accept any liabilities with respect to the programs. Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at: international.cengage.com/region Cengage Learning products are represented in Canada by Nelson Education, Ltd. To learn more about Course Technology, visit www.cengage.com/coursetechnology Purchase any of our products at your local college store or at our preferred online store www.cengagebrain.com

Printed in the United States of America 1 2 3 4 5 6 7 16 15 14 13 12 11

A_C7785_FM.1c ii

1/19/11 10:21 AM

BRIEF TABLE OF CONTENTS

Part One Fundamentals of C++ Programming

1

Chapter 1 Getting Started

3

Chapter 2 Data Types, Declarations, and Displays

37

Chapter 3 Assignment and Interactive Input

79

Chapter 4 Selection

137

Chapter 5 Repetition

179

Chapter 6 Modularity Using Functions

225

Chapter 7 Arrays

291

Chapter 8 Arrays and Pointers

341

Chapter 9 I/O Streams and Data Files

387

Part Two Object-Oriented Programming

431

Chapter 10 Introduction to Classes

433

Chapter 11 Adding Functionality to Your Classes

491 Brief Table of Contents

A_C7785_FM.1c iii

iii

1/18/11 10:42 AM

iv

Brief Table of Contents

Chapter 12 Extending Your Classes

539

Chapter 13 The Standard Template Library

Part Three Additional Topics

573

603

Chapter 14 The string Class and Exception Handling

605

Chapter 15 Strings as Character Arrays

665

Chapter 16 Data Structures

701

Appendixes Appendix A Operator Precedence Table

729

Appendix B ASCII Character Codes

731

Appendix C Bit Operations

Online Only

Appendix D Floating-Point Number Storage

Online Only

Appendix E

A_C7785_FM.1c iv

Solutions to Selected Exercises

733

Index

753

1/18/11 10:42 AM

CONTENTS

Part One Fundamentals of C++ Programming

1

Chapter 1 Getting Started

3

1.1 Introduction to Programming Algorithms and Procedures Classes and Objects Program Translation 1.2 Function and Class Names The main() Function 1.3 The cout Object 1.4 Programming Style Comments 1.5 Common Programming Errors 1.6 Chapter Summary 1.7 Chapter Supplement: Software Development Phase I: Development and Design Phase II: Documentation Phase III: Maintenance Backup

3 5 9 9 12 15 18 22 23 26 27 28 28 32 33 33

Chapter 2 Data Types, Declarations, and Displays

37

2.1 Data Types Integer Data Types Determining Storage Size Floating-Point Types Exponential Notation 2.2 Arithmetic Operations Expression Types Integer Division Negation Operator Precedence and Associativity 2.3 Variables and Declarations Declaration Statements Multiple Declarations Memory Allocation

37 38 42 44 45 48 51 52 52 53 57 59 62 64

Contents

A_C7785_FM.1c v

v

1/18/11 10:42 AM

vi

A_C7785_FM.1c vi

Contents

2.4 Common Programming Errors 2.5 Chapter Summary 2.6 Chapter Supplement: Bits, Bytes, and Binary Number Representations Bits and Bytes Binary, Hexadecimal, and Octal Numbers

70 71 72 72 74

Chapter 3 Assignment and Interactive Input

79

3.1 Assignment Operators Coercion Assignment Variations Accumulating Counting 3.2 Formatted Output The setiosflags() Manipulator Hexadecimal and Octal I/O 3.3 Mathematical Library Functions Casts 3.4 Interactive Keyboard Input A First Look at User-Input Validation 3.5 Symbolic Constants Placement of Statements 3.6 Common Programming Errors 3.7 Chapter Summary 3.8 Chapter Supplement: Errors, Testing, and Debugging Compile-Time and Runtime Errors Syntax and Logic Errors Testing and Debugging

79 84 85 86 88 93 97 99 106 111 117 121 127 128 132 132 133 134 134 135

Chapter 4 Selection

137

4.1 Relational Expressions Logical Operators A Numerical Accuracy Problem 4.2 The if-else Statement Compound Statements Block Scope One-Way Selection Problems Associated with the if-else Statement 4.3 Nested if Statements The if-else Chain

137 139 142 143 146 148 149 151 158 159

1/18/11 10:42 AM

Contents

4.4 4.5 4.6 4.7

A_C7785_FM.1c vii

The switch Statement Common Programming Errors Chapter Summary Chapter Supplement: A Closer Look at Testing

vii

167 173 174 176

Chapter 5 Repetition

179

5.1 The while Statement 5.2 Interactive while Loops Sentinels break and continue Statements The Null Statement 5.3 The for Statement Interactive for Loops Nested Loops 5.4 The do-while Statement Validity Checks 5.5 Common Programming Errors 5.6 Chapter Summary

180 188 194 197 198 201 208 209 217 219 220 222

Chapter 6 Modularity Using Functions

225

6.1 Function and Parameter Declarations Function Prototypes Calling a Function Defining a Function Placement of Statements Function Stubs Functions with Empty Parameter Lists Default Arguments Reusing Function Names (Overloading) Function Templates 6.2 Returning a Single Value Inline Functions Templates with a Return Value 6.3 Returning Multiple Values Passing and Using Reference Parameters 6.4 Variable Scope Scope Resolution Operator Misuse of Globals

226 227 228 229 234 234 235 236 237 238 244 250 251 257 258 267 271 272

1/18/11 10:42 AM

viii

A_C7785_FM.1c viii

Contents

6.5 Variable Storage Category Local Variable Storage Categories Global Variable Storage Categories 6.6 Common Programming Errors 6.7 Chapter Summary 6.8 Chapter Supplement: Generating Random Numbers Scaling

276 277 280 285 285 287 289

Chapter 7 Arrays

291

7.1 One-Dimensional Arrays Input and Output of Array Values 7.2 Array Initialization 7.3 Arrays as Arguments 7.4 Two-Dimensional Arrays Larger Dimensional Arrays 7.5 Common Programming Errors 7.6 Chapter Summary 7.7 Chapter Supplement: Searching and Sorting Methods Search Algorithms Sort Algorithms

292 296 303 307 313 319 323 324 325 325 333

Chapter 8 Arrays and Pointers

341

8.1 Introduction to Pointers Storing Addresses Using Addresses Declaring Pointers References and Pointers 8.2 Array Names as Pointers Dynamic Array Allocation 8.3 Pointer Arithmetic Pointer Initialization 8.4 Passing Addresses Passing Arrays Advanced Pointer Notation 8.5 Common Programming Errors 8.6 Chapter Summary

341 344 345 346 348 354 360 364 368 369 374 378 383 385

1/18/11 10:42 AM

Contents

Chapter 9 I/O Streams and Data Files

387

9.1 I/O File Stream Objects and Methods Files File Stream Objects File Stream Methods 9.2 Reading and Writing Text Files Reading from a Text File Standard Device Files Other Devices 9.3 Random File Access 9.4 File Streams as Function Arguments 9.5 Common Programming Errors 9.6 Chapter Summary 9.7 Chapter Supplement: The iostream Class Library File Stream Transfer Mechanism Components of the iostream Class Library In-Memory Formatting

388 388 389 390 403 406 411 412 416 419 423 423 426 426 426 428

Part Two Object-Oriented Programming

A_C7785_FM.1c ix

ix

431

Chapter 10 Introduction to Classes

433

10.1 Object-Based Programming A Class Is a Plan From Recipe to Class 10.2 Creating Your Own Classes Class Construction Terminology 10.3 Constructors Calling Constructors Overloaded and Inline Constructors Destructors Arrays of Objects 10.4 Examples Example 1: Constructing a Room Object Example 2: Constructing an Elevator Object

433 436 436 439 440 448 452 454 455 458 459 463 463 467

1/18/11 10:42 AM

x

A_C7785_FM.1c x

Contents

10.5 Class Scope and Duration Categories Static Class Members Friend Functions 10.6 Common Programming Errors 10.7 Chapter Summary 10.8 Chapter Supplement: Thinking in Terms of Objects Representing Problems with Models Modeling Classes

473 474 478 482 482 484 485 486

Chapter 11 Adding Functionality to Your Classes

491

11.1 Creating Class Operators Assignment Operator Copy Constructors Base/Member Initialization Operator Functions as Friends 11.2 How Methods Are Shared The this Pointer The Assignment Operator Revisited Objects as Arguments Notation 11.3 Data Type Conversions Built-in to Built-in Conversion Class to Built-in Conversion Built-in to Class Conversion Class to Class Conversion 11.4 Two Useful Alternatives: operator() and operator[] 11.5 Common Programming Errors 11.6 Chapter Summary 11.7 Chapter Supplement: Insides and Outsides Abstraction and Encapsulation Code Extensibility

491 499 500 503 504 508 509 511 514 515 519 520 520 522 525 529 533 533 535 537 537

Chapter 12 Extending Your Classes

539

12.1 Class Inheritance Access Specifications 12.2 Polymorphism 12.3 Dynamic Object Creation and Deletion 12.4 Pointers as Class Members Assignment Operators and Copy Constructors Reconsidered

540 541 547 552 562 565

1/18/11 10:42 AM

Contents

12.5 Common Programming Errors 12.6 Chapter Summary 12.7 Chapter Supplement: UML Class and Object Diagrams Class and Object Diagrams

568 568 569 570

Chapter 13 The Standard Template Library

573

13.1 The Standard Template Library 13.2 Linked Lists Using the STL list Class Using User-Defined Objects 13.3 Stacks Stack Implementation with the deque Class 13.4 Queues Queue Implementation with the deque Class 13.5 Common Programming Errors 13.6 Chapter Summary

574 579 581 586 590 592 598 599 602 602

Part Three Additional Topics

A_C7785_FM.1c xi

xi

603

Chapter 14 The string Class and Exception Handling

605

14.1 The string Class string Class Functions String Input and Output String Processing 14.2 Character Manipulation Methods Character I/O A Second Look at User-Input Validation 14.3 Exception Handling 14.4 Exceptions and File Checking Opening Multiple Files 14.5 Input Data Validation 14.6 Common Programming Errors 14.7 Chapter Summary 14.8 Chapter Supplement: Namespaces and Creating a Personal Library

606 607 609 613 622 627 632 634 640 644 649 656 656 657

1/18/11 10:42 AM

xii

Contents

Chapter 15 Strings as Character Arrays

665

15.1 C-String Fundamentals C-String Input and Output C-String Processing 15.2 Pointers and C-String Library Functions Library Functions Character-Handling Functions Conversion Functions 15.3 C-String Definitions and Pointer Arrays Pointer Arrays 15.4 Common Programming Errors 15.5 Chapter Summary

666 666 670 675 681 684 688 691 693 698 698

Chapter 16 Data Structures

701

16.1 Single Structures 16.2 Arrays of Structures 16.3 Structures as Function Arguments Passing a Pointer Returning Structures 16.4 Dynamic Structure Allocation 16.5 Unions 16.6 Common Programming Errors 16.7 Chapter Summary

702 708 712 716 718 721 724 727 728

Appendixes Appendix A Operator Precedence Table

729

Appendix B ASCII Character Codes

731

Appendix C Bit Operations

Online Only

Appendix D Floating-Point Number Storage

Online Only

Appendix E Solutions to Selected Exercises Index

A_C7785_FM.1c xii

733 753

1/18/11 10:42 AM

PREFACE The main goal of this fourth edition of A First Book of C++ remains the same as in previous editions: to introduce, develop, and reinforce well-organized programming skills using C++. All topics are presented in a clear, unambiguous, and accessible manner to beginning students. Students should be familiar with fundamental algebra, but no other prerequisites are assumed. Therefore, like the first three editions, this new edition begins by providing a strong foundation in structured programming. This foundation is then expanded to an object-oriented design and programming approach in a pedagogically sound, achievable progression. In addition to a number of minor changes throughout the book, the major changes in this edition are the following: •

Part I has been restructured to include arrays, files, and pointers, so it can be used as the basis for a complete introductory semester course in C++. • The four chapters covering object-oriented programming have been revised and moved to Part II so that they form a logical continuation from structured programming to object-oriented programming. • More than 50 new exercises have been added, and all exercises are labeled to indicate their function (Review, Practice, Program, Modify, Debug, Desk check, or For thought). • Three new Chapter Supplements have been added to introduce the fundamentals of object-oriented design and the Unified Modeling Language (UML). • A complete set of case studies has been added and is available on the Cengage Web site, login.cengage.com, for instructors to distribute. The following features from the third edition have been retained: •

Fundamentals of software engineering are discussed from both procedural and object-oriented viewpoints. • Each chapter contains a Common Programming Errors section that describes problems beginning C++ programmers typically encounter. • The ANSI/ISO C++ iostream library and namespace mechanism are used in all programs. • Exception handling is discussed in a separate section, with practical applications of exception handling included throughout the book. • The C++ string class is covered. • A thorough discussion is included of input data validation and functions to check the numerical data type of input items and allow reentering invalid numerical types. In practical terms, this book has been written to support both a one- and two-semester technical C++ programming course; the only prerequisite is that students should be familiar with fundamental algebra. This book is constructed to be flexible enough so that instructors can mold the book to their preferences for topic sequence. This flexibility is achieved in the following ways. Part I includes the basic structured syntax, flow control, and modularity topics needed for a thorough understanding of C++’s structural features. With the topics of arrays (Chapter 7) and files (Chapter 9) moved to Part I, this part now provides a comprehensive one-semester

Preface

A_C7785_FM.1c xiii

xiii

1/18/11 10:42 AM

xiv

Preface

course. As Chapters 7 and 9 have been written to depend only on Chapters 1 through 6, their order of presentation (arrays first and files second, or vice versa) is entirely up to the instructor’s discretion. With time permitting, the basics of classes, introduced in Chapter 10, can also be covered to create a one-semester course with an introduction to object-oriented programming. Figure 1 illustrates this one-semester topic dependency, and Figure 2 shows the topic dependency chart for the entire book. Arrays Chapter 7 Part I Files Chapters 1 to 6

Chapter 9 Objects Chapter 10

Figure 1 Topic dependency for a one-semester course

Part II (Chapters 10 to 13) Object-Oriented Programming Part I Procedural Programming Part III (Chapters 14 to 16)

Figure 2 Topic dependency chart

Distinctive Features of This Book Writing Style

One thing I have found to be essential in my own classes is that after the instructor sets the stage in class, the assigned book must continue to encourage, nurture, and assist students in acquiring and “owning” the material. To do this, the book must be written in a manner that makes sense to students. My primary concern, and one of the distinctive features of this book, is that it has been written for students. Therefore, I believe the writing style used to convey the concepts is one of the most important aspects of this book.

A_C7785_FM.1c xiv

1/18/11 10:42 AM

Preface

xv

Software Engineering Rather than simply introduce students to programming in C++, this book introduces students to the fundamentals of software engineering, from both a procedural and object-oriented viewpoint. It begins with a discussion of these two programming approaches in Section 1.1 and is reinforced throughout the book. Introduction to References and Pointers A unique feature of my book A First Book of ANSI C was introducing pointer concepts early by displaying addresses of variables and then using other variables to store these addresses. This approach always seemed a more logical method of understanding pointers than the indirection description in vogue at the time A First Book of ANSI C was released. I have since been pleased to see that using an output function to display addresses has become a standard way of introducing pointers. Although this approach is no longer a unique feature of this book, I’m proud of its presentation and continue to use it in this book. References are also introduced early, in Chapter 6, before the introduction of pointers in Chapter 8. Program Testing

Every C++ program in this book has been compiled and run successfully and has been quality-assurance tested with Microsoft Visual C++ 2010. Source code for all programs is available for student download at www.cengagebrain.com. Using this source code enables students to experiment with and extend the existing programs and modify them more easily, as required for a number of end-of-section exercises.

Pedagogical Features To facilitate the goal of making C++ accessible as a first-level course, the following pedagogical features have been incorporated into the book. Point of Information Boxes These shaded boxes in each chapter highlight important concepts, useful technical points, programming tips, and tricks used by professional programmers. End-of-Section Exercises Almost every section in the book contains numerous and diverse skill-building and programming exercises. In addition, solutions to selected exercises are given in Appendix E. Pseudocode Descriptions Pseudocode is used throughout the book. Flowchart symbols are introduced but are used only in illustrating flow-of-control constructs. Common Programming Errors and Chapter Summary

Each chapter ends with a section on common programming errors and a summary of the main topics covered in the chapter.

Appendixes This book includes appendixes on operator precedence, ASCII codes, and solu-

tions to selected exercises. Additional appendixes on bit operations and floating-point number storage are available for student download at www.cengagebrain.com.

A_C7785_FM.1c xv

1/18/11 10:42 AM

xvi

Preface

Note to students: Microsoft offers a free C++ compiler and development system called Microsoft Visual C++ Express 2010. To get this development system, go to www.microsoft.com/ express/Downloads/#2010-Visual-CPP and select English as the language. The vc_web file is downloaded automatically to your Downloads folder. (If you don’t have this folder, do a search to see where the file was downloaded.) After this file is downloaded, double-click it to install Visual C++ Express 2010. All programs in this book can be run as Visual C++ Express 2010 CLR Console Applications or Win32 Console Applications programs, with two additions: •

The code line #includeƒ“stdafx.h” must be added at the beginning of the program. • The code line cin.ignore(); must be included before the return statement. These added code lines hold the window open after the program runs so that you can view it. Pressing Enter terminates the program and closes the window. For example, to compile and run Program 1.1 in this book, you should enter the program in Visual C++ Express 2010 as follows: #includeƒ"stdafx.h"ƒƒ//ƒneededƒforƒVisualƒC++ƒExpressƒ2010 #includeƒ usingƒnamespaceƒstd; intƒmain() { ƒƒcoutƒ