Tải bản đầy đủ (.pdf) (756 trang)

Diane zak introduction to programming with c++

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (8.02 MB, 756 trang )

AN INTRODUCTION TO
PROGRAMMING WITH C++
This page intentionally left blank
AN INTRODUCTION TO
PROGRAMMING WITH C++
DIANE ZAK
SIXTH EDITION
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
© 2011 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.
Library of Congress Control Number: 2009941969
ISBN-13: 978-0-538-46652-3
ISBN-10: 0-538-46652-9
Course Technology
20 Channel Center Street
Boston, MA 02210
USA
Some of the product names and company names used in this book have been
used for identifi cation purposes only and may be trademarks or registered
trademarks of their respective manufacturers and sellers.
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.
Cengage Learning is a leading provider of customized learning solutions with
offi ce locations around the globe, including Singapore, the United Kingdom,


Australia, Mexico, Brazil, and Japan. Locate your local offi ce at:
www.cengage.com/global
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
An Introduction to Programming with C++,
Sixth Edition
Diane Zak
Executive Editor: Marie Lee
Acquisitions Editor: Amy Jollymore
Freelance Product Manager: Tricia Coia
Senior Content Project Manager: Jill Braiewa
Editorial Assistant: Zina Kresin
Art Director: Marissa Falco
Text Designer: Shawn Girsberger
Print Buyer: Julio Esperas
Proofreader: Andy Smith, Green Pen QA
Indexer: Michael Brackney
Compositor: Integra Software Services
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 cengage.com/permissions
Further permissions questions can be emailed to

Printed in the United States of America
1 2 3 4 5 6 7 16 15 14 13 12 11 10
This page intentionally left blank

vi
Brief Contents
Preface . . . . . . . . . . . . . . . . . . . . . .xiv
CHAPTER 1 An Introduction to Programming . . . . . . . . . . . . 1
CHAPTER 2 Beginning the Problem-Solving Process. . . . . . . . 22
CHAPTER 3 Variables and Constants . . . . . . . . . . . . . . 51
CHAPTER 4 Completing the Problem-Solving Process . . . . . . . 77
CHAPTER 5 The Selection Structure . . . . . . . . . . . . . . 119
CHAPTER 6 More on the Selection Structure. . . . . . . . . . . 163
CHAPTER 7 The Repetition Structure . . . . . . . . . . . . . . 213
CHAPTER 8 More on the Repetition Structure . . . . . . . . . . 264
CHAPTER 9 Value-Returning Functions . . . . . . . . . . . . . 308
CHAPTER 10 Void Functions . . . . . . . . . . . . . . . . . . 370
CHAPTER 11 One-Dimensional Arrays . . . . . . . . . . . . . . 419
CHAPTER 12 Two-Dimensional Arrays . . . . . . . . . . . . . . 486
CHAPTER 13 Strings. . . . . . . . . . . . . . . . . . . . . . 524
CHAPTER 14 Sequential Access Files . . . . . . . . . . . . . . 582
APPENDIX A Answers to Mini-Quizzes and Labs . . . . . . . . . . 626
APPENDIX B C++ Keywords . . . . . . . . . . . . . . . . . . 690
vii
APPENDIX C ASCII Codes . . . . . . . . . . . . . . . . . . . 691
APPENDIX D How to Use Microsoft Visual C++ . . . . . . . . . . 693
APPENDIX E How to Use Dev-C++. . . . . . . . . . . . . . . . 694
APPENDIX F Classes and Objects . . . . . . . . . . . . . . . . 695
Index . . . . . . . . . . . . . . . . . . . . . . 721
viii
Contents
Preface . . . . . . . . . . . . . . . . . . . . . .xiv
CHAPTER 1 An Introduction to Programming . . . . . . . . . . . . 1
Programming a Computer . . . . . . . . . . . . . . . . . . . . . . . 2

The Programmer’s Job . . . . . . . . . . . . . . . . . . . . . . . 2
Do I Have What It Takes to Be a Programmer?. . . . . . . . . . . . . 2
Employment Opportunities . . . . . . . . . . . . . . . . . . . . . 3
A Brief History of Programming Languages. . . . . . . . . . . . . . . . 4
Machine Languages . . . . . . . . . . . . . . . . . . . . . . . . 4
Assembly Languages . . . . . . . . . . . . . . . . . . . . . . . . 4
High-Level Languages. . . . . . . . . . . . . . . . . . . . . . . . 4
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
The Sequence Structure . . . . . . . . . . . . . . . . . . . . . . 6
The Selection Structure . . . . . . . . . . . . . . . . . . . . . . . 7
The Repetition Structure . . . . . . . . . . . . . . . . . . . . . . 9
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
CHAPTER 2 Beginning the Problem-Solving Process. . . . . . . . 22
Problem Solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Solving Everyday Problems . . . . . . . . . . . . . . . . . . . . . . . 23
Creating Computer Solutions to Problems . . . . . . . . . . . . . . . . 24
Step 1—Analyze the Problem . . . . . . . . . . . . . . . . . . . . . . 25
Step 2—Plan the Algorithm . . . . . . . . . . . . . . . . . . . . . . . 27
Step 3—Desk-Check the Algorithm . . . . . . . . . . . . . . . . . . . 31
The Gas Mileage Problem. . . . . . . . . . . . . . . . . . . . . . . . 34
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
CHAPTER 3 Variables and Constants . . . . . . . . . . . . . . 51
Beginning Step 4 in the Problem-Solving Process . . . . . . . . . . . . . 52
Internal Memory . . . . . . . . . . . . . . . . . . . . . . . . . . 52

ix
Selecting a Name for a Memory Location . . . . . . . . . . . . . . . . 53
Revisiting the Treyson Mobley Problem . . . . . . . . . . . . . . . . 54
Selecting a Data Type for a Memory Location . . . . . . . . . . . . . . 55
How Data Is Stored in Internal Memory . . . . . . . . . . . . . . . . 57
Selecting an Initial Value for a Memory Location . . . . . . . . . . . . . 60
Declaring a Memory Location . . . . . . . . . . . . . . . . . . . . . . 62
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
CHAPTER 4 Completing the Problem-Solving Process . . . . . . . . 77
Finishing Step 4 in the Problem-Solving Process . . . . . . . . . . . . . 78
Getting Data from the Keyboard . . . . . . . . . . . . . . . . . . . . . 79
Displaying Messages on the Computer Screen . . . . . . . . . . . . . . 81
Arithmetic Operators in C++ . . . . . . . . . . . . . . . . . . . . . . 83
Type Conversions in Arithmetic Expressions . . . . . . . . . . . . . 84
The static_cast Operator . . . . . . . . . . . . . . . . . . . . 86
Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . 87
Step 5—Desk-Check the Program . . . . . . . . . . . . . . . . . . . . 90
Step 6—Evaluate and Modify the Program . . . . . . . . . . . . . . . . 92
Arithmetic Assignment Operators . . . . . . . . . . . . . . . . . . . . 97
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .105
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .107
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109
CHAPTER 5 The Selection Structure . . . . . . . . . . . . . . 119
Making Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . .120
Flowcharting a Selection Structure . . . . . . . . . . . . . . . . . . .123
Coding a Selection Structure in C++. . . . . . . . . . . . . . . . . . .125

Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . .127
Swapping Numeric Values . . . . . . . . . . . . . . . . . . . . . .128
Displaying the Sum or Difference . . . . . . . . . . . . . . . . . .130
Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . .132
Using the Truth Tables . . . . . . . . . . . . . . . . . . . . . . .134
Calculating Gross Pay . . . . . . . . . . . . . . . . . . . . . . .135
Pass/ Fail Program . . . . . . . . . . . . . . . . . . . . . . . . .137
Converting a Character to Uppercase or Lowercase. . . . . . . . . . . .140
Formatting Numeric Output . . . . . . . . . . . . . . . . . . . . . . .141
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .152
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .154
CHAPTER 6 More on the Selection Structure. . . . . . . . . . . 163
Making Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . .164
Flowcharting a Nested Selection Structure . . . . . . . . . . . . . . . .168
Coding a Nested Selection Structure . . . . . . . . . . . . . . . . . .170
x
CONTENTS
Logic Errors in Selection Structures . . . . . . . . . . . . . . . . . . .173
First Logic Error: Using a Compound Condition Rather Than a
Nested Selection Structure . . . . . . . . . . . . . . . . . . . . .175
Second Logic Error: Reversing the Outer and Nested Decisions . . . .177
Third Logic Error: Using an Unnecessary Nested Selection
Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178
Multiple-Alternative Selection Structures . . . . . . . . . . . . . . . . .180
The switch Statement. . . . . . . . . . . . . . . . . . . . . . .183
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .196
Key Terms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .196
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .197

Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .200
CHAPTER 7 The Repetition Structure . . . . . . . . . . . . . . 213
Repeating Program Instructions . . . . . . . . . . . . . . . . . . . . .214
Using a Pretest Loop to Solve a Real-World Problem . . . . . . . . . . .216
Flowcharting a Pretest Loop . . . . . . . . . . . . . . . . . . . . . .219
The while Statement . . . . . . . . . . . . . . . . . . . . . . . . .221
Using Counters and Accumulators . . . . . . . . . . . . . . . . . . . .224
The Sales Express Program . . . . . . . . . . . . . . . . . . . . .225
Counter-Controlled Pretest Loops . . . . . . . . . . . . . . . . . . . .228
The for Statement . . . . . . . . . . . . . . . . . . . . . . . . . .231
The Holmes Supply Program. . . . . . . . . . . . . . . . . . . . .233
The Colfax Sales Program. . . . . . . . . . . . . . . . . . . . . .236
Another Version of the Miller Incorporated Program . . . . . . . . . .238
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .249
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .250
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .251
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .254
CHAPTER 8 More on the Repetition Structure . . . . . . . . . . 264
Posttest Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . .265
Flowcharting a Posttest Loop . . . . . . . . . . . . . . . . . . . . . .267
The do while Statement . . . . . . . . . . . . . . . . . . . . . . .270
Nested Repetition Structures . . . . . . . . . . . . . . . . . . . . . .273
The Asterisks Program . . . . . . . . . . . . . . . . . . . . . . . . .275
The Savings Calculator Program. . . . . . . . . . . . . . . . . . . . .283
The pow Function . . . . . . . . . . . . . . . . . . . . . . . . .284
Coding the Savings Calculator Program . . . . . . . . . . . . . . .286
Modifying the Savings Calculator Program . . . . . . . . . . . . . . . .287
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .297
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .298
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .298

Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .300
CHAPTER 9 Value-Returning Functions . . . . . . . . . . . . . 308
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .309
The Hypotenuse Program . . . . . . . . . . . . . . . . . . . . . . . .310
Finding the Square Root of a Number . . . . . . . . . . . . . . . .310
xi
The Random Addition Problems Program . . . . . . . . . . . . . . . . .313
Generating Random Integers . . . . . . . . . . . . . . . . . . . .314
Creating Program-Defined Value-Returning Functions . . . . . . . . . . .322
Calling a Function . . . . . . . . . . . . . . . . . . . . . . . . . . .326
Function Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . .330
The Plano Elementary School Program. . . . . . . . . . . . . . . . . .333
The Area Calculator Program . . . . . . . . . . . . . . . . . . . . . .336
The Scope and Lifetime of a Variable . . . . . . . . . . . . . . . . . .340
The Bonus Calculator Program. . . . . . . . . . . . . . . . . . . .340
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .357
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .358
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .359
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .362
CHAPTER 10 Void Functions . . . . . . . . . . . . . . . . . . 370
Void Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .371
Passing Variables to a Function . . . . . . . . . . . . . . . . . . . . .376
Reviewing Passing Variables by Value . . . . . . . . . . . . . . . .377
Passing Variables by Reference . . . . . . . . . . . . . . . . . . .379
The Salary Program . . . . . . . . . . . . . . . . . . . . . . . . . .384
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .401
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .402
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .402
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .406
CHAPTER 11 One-Dimensional Arrays . . . . . . . . . . . . . . 419

Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .420
One-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . .420
Declaring and Initializing a One-Dimensional Array . . . . . . . . . . .422
Entering Data into a One-Dimensional Array . . . . . . . . . . . . . .424
Displaying the Contents of a One-Dimensional Array . . . . . . . . . .426
Coding the XYZ Company’s Sales Program . . . . . . . . . . . . . .427
Passing a One-Dimensional Array to a Function . . . . . . . . . . . . . .433
The Moonbucks Coffee Program—Calculating a Total and Average . . . . .436
The KL Motors Program—Searching an Array. . . . . . . . . . . . . . .439
The Hourly Rate Program—Accessing an Individual Element . . . . . . . .442
The Random Numbers Program . . . . . . . . . . . . . . . . . . . . .444
Sorting the Data Stored in a One-Dimensional Array . . . . . . . . . . . .454
Parallel One-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . .461
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .473
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .474
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .474
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .478
CHAPTER 12 Two-Dimensional Arrays . . . . . . . . . . . . . . 486
Using Two-Dimensional Arrays. . . . . . . . . . . . . . . . . . . . . .487
Declaring and Initializing a Two-Dimensional Array . . . . . . . . . . .489
Entering Data into a Two-Dimensional Array . . . . . . . . . . . . . .491
xii
CONTENTS
Displaying the Contents of a Two-Dimensional Array . . . . . . . . . .494
Coding the Caldwell Company’s Orders Program . . . . . . . . . . .495
Accumulating the Values Stored in a Two-Dimensional Array . . . . . . . .498
Searching a Two-Dimensional Array . . . . . . . . . . . . . . . . . . .500
Passing a Two-Dimensional Array to a Function . . . . . . . . . . . . . .507
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .515
Key Term . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .516

Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .516
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .517
CHAPTER 13 Strings. . . . . . . . . . . . . . . . . . . . . . 524
The string Data Type. . . . . . . . . . . . . . . . . . . . . . . . .525
The Creative Sales Program . . . . . . . . . . . . . . . . . . . . . .526
The getline Function . . . . . . . . . . . . . . . . . . . . . . .527
The ignore Function . . . . . . . . . . . . . . . . . . . . . . .531
The ZIP Code Program . . . . . . . . . . . . . . . . . . . . . . . . .535
Determining the Number of Characters Contained in
a string Variable . . . . . . . . . . . . . . . . . . . . . . . . .535
Accessing the Characters Contained in a string Variable. . . . . . .538
The Rearranged Name Program . . . . . . . . . . . . . . . . . . . . .544
Searching the Contents of a string Variable. . . . . . . . . . . . .544
The Annual Income Program . . . . . . . . . . . . . . . . . . . . . .547
Removing Characters from a string Variable . . . . . . . . . . . .548
Replacing Characters in a string Variable. . . . . . . . . . . . . .551
The Social Security Number Program . . . . . . . . . . . . . . . . . .553
Inserting Characters Within a string Variable . . . . . . . . . . . .554
The Company Name Program . . . . . . . . . . . . . . . . . . . . . .556
Duplicating a Character Within a string Variable. . . . . . . . . . .557
Concatenating Strings . . . . . . . . . . . . . . . . . . . . . . .558
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .568
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .570
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .570
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .574
CHAPTER 14 Sequential Access Files . . . . . . . . . . . . . . 582
File Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .583
The CD Collection Program . . . . . . . . . . . . . . . . . . . . . . .583
Creating File Objects . . . . . . . . . . . . . . . . . . . . . . . . . .585
Opening a Sequential Access File . . . . . . . . . . . . . . . . . . . .586

Determining Whether a File Was Opened Successfully . . . . . . . . .589
Writing Data to a Sequential Access File . . . . . . . . . . . . . . . . .590
Reading Information from a Sequential Access File . . . . . . . . . . . .592
Testing for the End of a Sequential Access File . . . . . . . . . . . . . .594
Closing a Sequential Access File . . . . . . . . . . . . . . . . . . . .595
Coding the CD Collection Program. . . . . . . . . . . . . . . . . . . .596
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .614
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .614
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .615
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .618
xiii
APPENDIX A Answers to Mini-Quizzes and Labs . . . . . . . . . . 626
APPENDIX B C++ Keywords . . . . . . . . . . . . . . . . . . 690
APPENDIX C ASCII Codes . . . . . . . . . . . . . . . . . . . 691
APPENDIX D How to Use Microsoft Visual C++ . . . . . . . . . . 693
APPENDIX E How to Use Dev-C++. . . . . . . . . . . . . . . . 694
APPENDIX F Classes and Objects . . . . . . . . . . . . . . . . 695
Object-Oriented Terminology . . . . . . . . . . . . . . . . . . . . . .696
Defining a Class in C++ . . . . . . . . . . . . . . . . . . . . . . . .697
Instantiating an Object and Referring to a Public Member . . . . . . . . .700
Example 1—A Class that Contains Public Data Members Only . . . . . . .702
Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . .704
Example 2—A Class that Contains a Private Data Member
and Public Member Methods . . . . . . . . . . . . . . . . . . . . . .706
Example 3—Using a Class that Contains Two Constructors . . . . . . . .709
Example 4—A Class that Contains Overloaded Methods . . . . . . . . . .712
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .716
Key Terms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .717
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . .718
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .720

Index . . . . . . . . . . . . . . . . . . . . . . 721
xiv
Preface
An Introduction to Programming with C++, Sixth Edition uses the C++ pro-
gramming language to teach programming concepts.  is book is designed for
a beginning programming course. Although the book provides instructions for
using the Microsoft
®
Visual C++
®
and Dev-C++ compilers, it can be used with
most C++ compilers, often with little or no modifi cation.
Organization and Coverage
An Introduction to Programming with C++, Sixth Edition contains 14 chapters
and several appendices. In order to provide the most up-to-date instructions for
using the Microsoft Visual C++ and Dev-C++ compilers, Appendices D and E
are available online. You can obtain the appendices by connecting to the Course
Technology Web site (www.cengage.com/coursetechnology) and then navigating
to the page for this book. In the chapters, students with no previous program-
ming experience learn how to plan and create well-structured programs. By
the end of the book, students will have learned how to write programs using
the sequence, selection, and repetition structures, as well as how to create
and manipulate functions, sequential access fi les, arrays, strings, classes, and
objects.
Approach
An Introduction to Programming with C++, Sixth Edition is distinguished from
other textbooks because of its unique approach, which motivates students by
demonstrating why they need to learn the concepts and skills presented. Each
chapter begins with an introduction to one or more programming concepts.
 e concepts are illustrated with code examples and sample programs.  e

sample programs allow the student to observe how the current concept can be
used before they are introduced to the next concept.  e concepts are taught
using standard C++ commands. Following the concept portion in each chapter
(except Chapter 1) are fi ve labs: Stop and Analyze, Plan and Create, Modify,
Desk-Check, and Debug. Each lab teaches students how to apply the chapter
concepts; however, each does so in a diff erent way.
Features
An Introduction to Programming with C++, Sixth Edition is an exceptional text-
book because it also includes the following features:
READ THIS BEFORE YOU BEGIN  is section is consistent with Course
Technology’s unequaled commitment to helping instructors introduce
technology into the classroom. Technical considerations and assumptions
about hardware, software, and default settings are listed in one place to help
instructors save time and eliminate unnecessary aggravation.
LABS Each chapter contains fi ve labs that teach students how to apply
the concepts taught in the chapter to real-world problems. In the fi rst
lab, which is the Stop and Analyze lab, students are expected to stop
and analyze an existing program. Students plan and create a program in the
Plan and Create lab, which is the second lab.  e third lab is the Modify lab.
 is lab requires students to modify an existing program.  e fourth lab is
the Desk-Check lab, in which students follow the logic of a program by desk-
checking it.  e fi fth lab is the Debug lab.  is lab gives students an opportu-
nity to fi nd and correct the errors in an existing program.
STANDARD C++ SYNTAX Like the previous edition of the book, this edition
uses the standard C++ syntax in the examples, sample programs, and exer-
cises in each chapter.
TIP  ese notes provide additional information about the current con-
cept. Examples include alternative ways of writing statements, warnings
about common mistakes made when using a particular command, and
reminders of related concepts learned in previous chapters.

PSEUDOCODE AND FLOWCHARTS Although pseudocode is the primary
tool used when planning the programs in each chapter, fl owcharts also are
provided for many of the programs. If the fl owchart is not in the chapter
itself, the student is directed to the Cpp6\Chapxx\ChxxFlowcharts.pdf fi le,
where xx is the chapter number.
MINI-QUIZZES Mini-quizzes are strategically placed to test students’
knowledge at various points in each chapter. Answers to the quiz questions
are provided in Appendix A, allowing students to determine whether they
have mastered the material covered thus far before continuing with the
chapter.
SUMMARY A Summary section follows the labs in each chapter.  e Sum-
mary section recaps the programming concepts and commands covered in
the chapter.
KEY TERMS Following the Summary section in each chapter is a list-
ing of the key terms introduced throughout the chapter, along with their
defi nitions.
REVIEW QUESTIONS Review Questions follow the Key Terms section in
each chapter.  e Review Questions test the students’ understanding of what
they learned in the chapter.
PAPER AND PENCIL EXERCISES  e Review Questions are fol-
lowed by Pencil and Paper Exercises, which are designated as TRY
THIS, MODIFY THIS, INTRODUCTORY, INTERMEDIATE,
ADVANCED, and SWAT THE BUGS.  e answers to the TRY THIS Exer-
cises are provided at the end of the chapter.  e ADVANCED Exercises pro-
vide practice in applying cumulative programming knowledge or allow
students to explore alternative solutions to programming tasks.  e SWAT
THE BUGS Exercises provide an opportunity for students to detect and cor-
rect errors in one or more lines of code.
xv
Organization and Coverage

COMPUTER EXERCISES  e Computer Exercises provide students
with additional practice of the skills and concepts they learned in the
chapter.  e Computer Exercises are designated as TRY THIS,
MODIFY THIS, INTRODUCTORY, INTERMEDIATE, ADVANCED, and
SWAT THE BUGS.  e answers to the TRY THIS Exercises are provided at
the end of the chapter.  e ADVANCED Exercises provide practice in apply-
ing cumulative programming knowledge or allow students to explore alterna-
tive solutions to programming tasks.  e SWAT THE BUGS Exercises
provide an opportunity for students to detect and correct errors in an exist-
ing program.
New to This Edition!
STD NAMESPACE Rather than including a using directive for each
standard object used in a program, all programs now contain the
using
namespace std;
directive.
STRING CLASS  e string class is now covered in Chapter 13. In the
chapter, students learn how to declare and utilize
string variables and
string named constants in a program.  ey also learn how to concatenate
strings and use many of the functions available in the
string class.
CHAPTERS 3 AND 4 Chapters 3 and 4 from the previous edition of the
book have been redesigned to make the material easier for students to
comprehend. Chapter 3 now covers only variables and named constants,
which are challenging concepts for beginner programmers. Chapter 4
shows the student how to get numeric and character input from the
keyboard, write assignment statements, and display information on
the computer screen. Chapter 4 also covers the last three steps in the
problem-solving process.

ARRAYS One-dimensional arrays and two-dimensional arrays are now cov-
ered in separate chapters. One-dimensional arrays are covered in Chapter 11,
and two-dimensional arrays are covered in Chapter 12.
APPENDIX A  e answers to both the Mini-Quiz questions and the Labs are
now located in one convenient place in the book: Appendix A.
APPENDICES D AND E Appendix D contains the instructions for using the
Microsoft Visual C++ compiler, and Appendix E contains the instructions
for using the Dev-C++ compiler. In order to provide the most up-to-date
instructions for using both compilers, Appendices D and E are available
online. You can obtain the appendices by connecting to the Course Technol-
ogy Web site (www.cengage.com/coursetechnology) and then navigating to the
page for this book.
APPENDIX F Appendix F covers Classes and Objects.  is topic was origi-
nally covered in Chapter 14 in the previous edition of the book.
NEW EXAMPLES, SAMPLE PROGRAMS, AND EXERCISES Each chapter
has been updated with new examples, sample programs, and exercises.
NEW FORMAT  e book has a new, more convenient format. All of the
questions and exercises are now located at the end of the chapter.
xvi
PREFACE Organization and Coverage
Instructor Resources and Supplements
All of the resources available with this book are provided to the instructor on
a single CD-ROM. Many also can be found on the Course Technology Web
site (www.cengage.com/coursetechnology).
ELECTRONIC INSTRUCTOR’S MANUAL  e Instructor’s Manual that
accompanies this textbook includes additional instructional material to assist
in class preparation, including Sample Syllabi, Chapter Outlines, Technical
Notes, Lecture Notes, Quick Quizzes, Teaching Tips, Discussion Topics, and
Additional Case Projects.
EXAMVIEW

®
 is textbook is accompanied by ExamView, a powerful test-
ing software package that allows instructors to create and administer printed,
computer (LAN-based), and Internet exams. ExamView includes hundreds
of questions that correspond to the topics covered in this text, enabling
students to generate detailed study guides that include page references for
further review.  e computer-based and Internet testing components allow
students to take exams at their computers, and also save the instructor time
by grading each exam automatically.
MICROSOFT
®
POWERPOINT
®
PRESENTATIONS  is book off ers Micro-
soft PowerPoint slides for each chapter.  ese are included as a teaching aid
for classroom presentation, to make available to students on the network for
chapter review, or to be printed for classroom distribution. Instructors can
add their own slides for additional topics they introduce to the class.
DATA FILES Data Files are necessary for completing the Labs and Com-
puter Exercises in this book.  e Data Files are provided on the Instructor
Resources CD-ROM and also may be found on the Course Technology Web
site at www.cengage.com/coursetechnology.
SOLUTION FILES Solutions to the Labs, Review Questions, Pencil and Paper
Exercises, and Computer Exercises are provided on the Instructor Resources
CD-ROM and also may be found on the Course Technology Web site at
www.cengage.com/coursetechnology.  e solutions are password protected.
FIGURE FILES  e sample programs that appear in the fi gures throughout
the book are provided on the Instructor Resources CD-ROM.
DISTANCE LEARNING Course Technology off ers online WebCT and
Blackboard courses for this text to provide the most complete and dynamic

learning experience possible. When you add online content to one of your
courses, you’re adding a lot: automated tests, topic reviews, quick quizzes,
and additional case projects with solutions. For more information on how to
bring distance learning to your course, contact your local Course Technology
sales representative.
xvii
Instructor Resources and Supplements
Acknowledgments
Writing a book is a team eff ort rather than an individual one. I would like
to take this opportunity to thank my team, especially Tricia Coia (Freelance
Product Manager), Jill Braiewa (Senior Content Project Manager), Sreejith
Govindan (Full Service Project Manager), and Nicole Ashton (Quality Assur-
ance).  ank you for your support, enthusiasm, patience, and hard work; it
made a diffi cult task much easier. Last, but certainly not least, I want to thank
Matthew Alimagham (Spartanburg Technical College) and Linda Cohen
(Forsyth Technical Community College) for their invaluable ideas and com-
ments. And an extra special thank you to Bill Tucker (Austin Community
College) for going way above and beyond to help me on this project. Your
attention to detail and your willingness to share your ideas and your experi-
ences with the previous edition of the book were very much appreciated.
Diane Zak
Got a Job in Computing . . . ?
We hope you enjoyed the Q&A on the inside front cover of this book. If youd
like to suggest that we interview someone you know, a recent graduate who has
landed an interesting job in computing, please send your suggestions via e-mail
to Amy Jollymore, Acquisitions Editor, at
xviii
PREFACE Got a Job in Computing . . . ?
xix
Read This Before

You Begin
Technical Information
Data Files
You will need data fi les to complete the Labs and Computer Exercises in this
book. Your instructor may provide the data fi les to you. You may obtain the
fi les electronically on the Course Technology Web site (www.cengage.com/
coursetechnology).
Each chapter in this book has its own set of data fi les, which are stored in a
separate folder within the Cpp6 folder.  e fi les for Chapter 4 are stored in
the Cpp6\Chap04 folder. Similarly, the fi les for Chapter 5 are stored in the
Cpp6\Chap05 folder.  roughout this book, you will be instructed to open
fi les from or save fi les to these folders.
You can use a computer in your school lab or your own computer to com-
plete the Labs and Computer Exercises in this book.
Using Your Own Computer
To use your own computer to complete the Labs and Computer Exercises
in this book, you will need a C++ compiler.  e book was written and Qual-
ity Assurance tested using Microsoft Visual C++ 2010. It also was tested
using Dev-C++. However, the book can be used with most C++ compilers,
often with little or no modifi cation. If your book came with a copy of Micro-
soft Visual C++, then you may install that on your computer and use it to
complete the material.
Visit Our Web Site
Additional materials designed for this textbook might be available through
the Course Technology Web site, www.cengage.com/coursetechnology. Search
this site for more details.
To the Instructor
To complete the Labs and Computer Exercises in this book, your stu-
dents must use a set of data fi les.  ese fi les are included on the Instructor
Resources CD-ROM.  ey may also be obtained electronically through the

Course Technology Web site at www.cengage.com/coursetechnology. Fol-
low the instructions in the Help fi le to copy the data fi les to your server or
standalone computer. You can view the Help fi le using a text editor such as
WordPad or Notepad. Once the fi les are copied, you should instruct your
users how to copy the fi les to their own computers or workstations.
 e material in this book was written and Quality Assurance tested using
Microsoft Visual C++ 2010. It also was tested using Dev-C++. However,
the book can be used with most C++ compilers, often with little or no
modifi cation.
Course Technology Data Files
You are granted a license to copy the data fi les to any computer or computer
network used by individuals who have purchased this book.
xx
PREFACE Technical Information
CHAPTER 1
An Introduction to
Programming
After studying Chapter 1, you should be able to:
Defi ne the terminology used in programming

Explain the tasks performed by a programmer
Describe the qualities of a good programmer
Understand the employment opportunities for programmers and 
software engineers
Explain the history of programming languages

Explain the sequence, selection, and repetition structures
Write simple algorithms using the sequence, selection, 
and repetition structures
2

CHAPTER 1 An Introduction to Programming
Programming a Computer
In essence, the word programming means giving a mechanism the directions
to accomplish a task. If you are like most people, you’ve already programmed
several mechanisms. For example, at one time or another, you probably
programmed your digital video recorder (DVR) in order to schedule a
timed-recording of a movie. You also may have programmed the speed dial
feature on your cell phone. Or you may have programmed your coff ee maker
to begin the brewing process before you wake up in the morning. Like your
DVR, cell phone, and coff ee maker, a computer also is a mechanism that can
be programmed.  e directions given to a computer are called
computer
programs
or, more simply, programs.  e people who write programs are
called
programmers. Programmers use a variety of special languages, called
programming languages, to communicate with the computer. Some popular
programming languages are C++, Visual Basic, C#, and Java. In this book,
you will use the C++ programming language.
The Programmer’s Job
When a company has a problem that requires a computer solution, typically
it is a programmer that comes to the rescue.  e programmer might be an
employee of the company; or he or she might be a freelance programmer,
which is a programmer who works on temporary contracts rather than for a
long-term employer. First, the programmer meets with the user, which is the
person (or persons) responsible for describing the problem. In many cases,
this person or persons also will eventually use the solution. Depending on
the complexity of the problem, multiple programmers may be involved, and
they may need to meet with the user several times.  e purpose of the initial
meetings is to determine the exact problem and to agree on the desired solu-

tion. After the programmer and user agree on the solution, the programmer
begins converting the solution into a computer program. During the con-
version phase, the programmer meets periodically with the user to deter-
mine whether the program fulfi lls the user’s needs and to refi ne any details
of the solution. When the user is satisfi ed that the program does what he
or she wants it to do, the programmer rigorously tests the program with
sample data before releasing it to the user. In many cases, the programmer
also provides the user with a manual that explains how to use the program.
As this process indicates, the creation of a good computer solution to a
problem—in other words, the creation of a good program—requires a great
deal of interaction between the programmer and the user.
Do I Have What It Takes to Be a Programmer?
According to the 2008–09 Edition of the Occupational Outlook Handbook
(OOH), published by the U.S. Department of Labor’s Bureau of Labor
Statistics, “When hiring programmers, employers look for people with the
necessary programming skills who can think logically and pay close attention
to detail. Programming calls for patience, persistence, and the ability to
work on exacting analytical work, especially under pressure. Ingenuity and
creativity also are particularly important when programmers design solutions
and test their work for potential failures. . . . Because programmers are
3
Programming a Computer
expected to work in teams and interact directly with users, employers want
programmers who are able to communicate with nontechnical personnel.
Business skills are also important, especially for those wishing to advance to
managerial positions.” If this description sounds like you, then you probably
have what it takes to be a programmer. But if it doesn’t sound like you, it’s
still worth your time to understand the programming process, especially
if you are planning a career in business. Knowing even a little bit about
the programming process will allow you, the manager of a department, to

better communicate your department’s needs to a programmer. It also will
give you the confi dence to question the programmer when he claims that
he can’t make the program modifi cation you requested. In addition, it will
help you determine whether the $15,000 quote you received from a freelance
programmer seems reasonable. Lastly, understanding the process a computer
programmer follows when solving a problem can help you solve problems
that don’t require a computer solution.
Employment Opportunities
But if, after reading this book, you are excited about the idea of working
as a computer programmer, here is some information on employment
opportunities. When searching for a job in computer programming, you will
encounter ads for “computer programmers” as well as for “computer software
engineers.” Although job titles and descriptions vary, computer software
engineers typically are responsible for designing an appropriate solution to a
user’s problem, while computer programmers are responsible for translating
the solution into a language that the computer can understand.  e process
of translating the solution is called
coding. Keep in mind that, depending on
the employer and the size and complexity of the user’s problem, the design
and coding tasks may be performed by the same employee, no matter what
his or her job title is. In other words, it’s not unusual for a software engineer
to code her solution, just as it’s not unusual for a programmer to have
designed the solution he is coding. Typically, computer software engineers
are expected to have at least a bachelor’s degree in computer engineering
or computer science, along with practical work experience. Computer pro-
grammers usually need at least an associate’s degree in computer science,
mathematics, or information systems, as well as profi ciency in one or more
programming languages. Computer programmers and software engineers
are employed in almost every industry, such as telecommunications com-
panies, software publishers, fi nancial institutions, insurance carriers, edu-

cational institutions, and government agencies. According to the May 2008
Occupational Employment Statistics, programmers held about 394,230 jobs
and had a mean annual wage of $73,470. Software engineers, on the other
hand, held about 494,160 jobs with a mean annual wage of $87,900.  e
Bureau of Labor Statistics predicts that employment of programmers will
decline slowly, decreasing by 4% from 2006 to 2016. However, the employ-
ment of computer software engineers is projected to increase by 38% over
the same period.  ere is a great deal of competition for programming and
software engineering jobs, so jobseekers will need to keep up to date with
the latest programming languages and technologies. More information about
computer programmers and computer software engineers can be found on
the Bureau of Labor Statistics Web site at www.bls.gov.
Programming
teams often
contain subject
matter experts,
who may or may
not be programmers. For
example, an accountant
might be part of a team
working on a program
that requires accounting
expertise.
4
CHAPTER 1 An Introduction to Programming
A Brief History of Programming Languages
Just as human beings communicate with each other through the use of
languages such as English, Spanish, Hindi, and Chinese, programmers use
a variety of programming languages to communicate with the computer. In
the next sections, you will follow the progression of programming languages

from machine languages to assembly languages, and then to high-level
languages.
Machine Languages
Within a computer, all data is represented by microscopic electronic switches
that can be either off or on.  e off switch is designated by a 0, and the on
switch is designated by a 1. Because computers can understand only these
on and off switches, the fi rst programmers had to write the program instruc-
tions using nothing but combinations of 0s and 1s; for example, a program
might contain the instruction
00101 10001 10000. Instructions written in
0s and 1s are called
machine language or machine code.  e machine lan-
guages (each type of machine has its own language) represent the only way to
communicate directly with the computer. As you can imagine, programming
in machine language is very tedious and error-prone and requires highly
trained programmers.
Assembly Languages
Slightly more advanced programming languages are called assembly
languages.  e
assembly languages simplify the programmer’s job by
allowing the programmer to use mnemonics in place of the 0s and 1s in the
program.
Mnemonics are memory aids—in this case, alphabetic abbreviations
for instructions. For example, most assembly languages use the mnemonic
ADD to represent an add operation and the mnemonic MUL to represent a
multiply operation. An example of an instruction written in an assembly
language is
ADD bx, ax. Programs written in an assembly language require
an
assembler, which also is a program, to convert the assembly instructions

into machine code—the 0s and 1s the computer can understand. Although
it is much easier to write programs in assembly language than in machine
language, programming in assembly language still is tedious and requires
highly trained programmers. Programs written in assembly language are
machine specifi c and usually must be rewritten in a diff erent assembly
language to run on a diff erent computer.
High-Level Languages
High-level languages represent the next major development in program-
ming languages.
High-level languages are a vast improvement over machine
and assembly languages, because they allow the programmer to use instruc-
tions that more closely resemble the English language. An example of an
instruction written in a high-level language is
grossPay = hours * rate.
In addition, high-level languages are more machine independent than are
machine and assembly languages. As a result, programs written in a high-
level language can be used on many diff erent types of computers. Programs
written in a high-level language usually require a compiler, which also is a

×