Upload
others
View
4
Download
1
Embed Size (px)
Citation preview
SIXTH E I) I T [ O N
FRANK L. FRIEDMAN
Temple University
ELLIOT B. KOFFMAN
Temple University
PEARSON
Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Contents
chapter zero Computer Science as a Career Path 35
chapter one Introchiction to Computers, Problem Solving,and Programming 49
1.1 Overview of Computers 50
Early Computers 50
Categories of Computers 51
Sharing Computer Resources 52
1.2 Computer Hardware 52
Memory 54
Main Memory 55
Secondary Memory 56
Central Processing Unit 58
Input/Output Devices 58
Computer Networks 59
The World Wide Web 61
1.3 Computer Software 62
Operating System 62
Application Software 64
Programming Languages 65
Object-Oriented Programming 66
1.4 Processing a High-Level Language Program 69
Executing a Program 71
1.5 The Software Development Method 72
Caution: Failure Is Part of the Process 75
1.6 Applying the Software Development Method 75
case study: Converting Miles to Kilometers 76
18 Contents
1.7 Professional Ethics for Computer Programmers 79
Privacy and Misuse of Data 79
Computer Hacking 79
Plagiarism and Software Piracy 80
Misuse of a Computer Resource 80
Chapter Review 81
Quick-Check Exercises 82
Review Questions 83
Answers to Quick-Check Exercises 84
Bjarne Stronstrup 85
chapter tWO Overview of C++ 87
2.1 C++ Language Elements 88
Comments 88
Compiler Directive #include 89
Namespace std 90
Function main 90
Declaration Statements 91
Executable Statements 92
Reserved Words and Identifiers 94
Reserved Words 94
Identifiers 94
Uppercase and Lowercase Letters 95
Data Types and Declarations 97
Data Types 97
string Class 100
Purpose of Data Types 101
Declarations 101
Constant Declarations 102
Executable Statements 105
Programs in Memory 105
Assignment Statements 105
Input/Output Operations 108
Input Statements 108
Program Output 110
The return Statement 112
General Form of a C++ Program 114
Comments in Programs 115
Arithmetic Expressions 117
Operators / and % 118
2.2
2.3
2.5
2.6
Contents 19
Data Type of a Mixed-Type Expression 120
Mixed-Type Assignment Statement 120
Expressions with Multiple Operators 121
Writing Mathematical Formulas in C++ 125
case study: Supermarket Coin Processor 127
Interactive Mode, Batch Mode, and Data Files 132
Input Redirection 132
Output Redirection 134
Common Programming Errors 135
Syntax Errors 136
Run-Time Errors 137
Undetected Errors 138
Logic Errors 139
Chapter Review 140
Quick-Check Exercises 142
Review Questions 143
Programming Projects 144
Answers to Quick-Check Exercises 147
Josee Lajoie 149
chapter three Top-Down Design with Functions and Classes 151
3.1 Building Programs from Existing Information 152
case study: Finding the Area and Circumferenceof a Circle 153
case study: Computing the Weight of a Batch
ofFlat Washers 155
3.2 Library Functions 160
C++ Library Functions 162
A Look Ahead 164
3.3 Top-Down Design and Structure Charts 166
case study: Drawing Simple Figures 166
3.4 Functions without Arguments 168
Function Prototypes 170
Function Definitions 170
Placement of Functions in a Program 172
Order of Execution of Functions 172
Advantages of Using Function Subprograms 174
3.5 Functions with Input Arguments 178
void Functions with Input Arguments 180
2.7
2.8
20 Contents
Functions with Input Arguments and a Single Result 180
Functions with Multiple Arguments 185
Argument/Parameter List Correspondence 186
The Function Data Area 187
Testing Fttnctions Using Drivers 187
3.6 Scope of Names 188
3.7 Extending C++ through Classes-Using Class string 191
The string Class 191
Declaring string Objects 193
Reading and Displaying string Objects 193
String Assignment and Concatenation 194
Operator Overloading 194
Dot Notation: Calling Functions length and at 194
Member Functions for Word-ProcessingOperations 195
Assigning a Substring to a string Object 196
3.8 Introduction to Computer Graphics (Optional) 198
Composition of a Window 198
Some Common Graphics Functions 199
Background Color and Foreground Color 201
Drawing Rectangles 202
Drawing Circles, Ellipses, and Arcs 203Pie Slices and Filled Ellipses 210
Adding Text to Drawings 212
3.9 Common Programming Errors 215
Separately Testing Function Subprograms 217
Chapter Review 218
Quick-Check Exercises 219
Review Questions 220
Programming Projects 221
Graphics Projects 225
Answers to Quick-Check Exercises 226
Mark Hall 228
chapter four Selection Structures: if and switch Statements 231
4.1 Control Structures 232
4.2 Logical Expressions 232
Logical Expressions Using Relational and EqualityOperators 233
Contents 21
Logical Expressions Using Logical Operators 234
Operator Precedence 236
Writing Conditions in C++ 238
Comparing Characters and Strings 240
Boolean Assignment 241
Writing bool Values 242
Using Integers to Represent Logical Values 242
4.3 Introduction to the if Control Statement 243
if Statement with Two Alternatives 244
if Statement with Dependent Statement 245
if Statement Conditions with Characters
and Strings 245
Format of the if Statement 247
if Statements with Compound Alternatives 249
Tracing an if Statement 250
Decision Steps in Algorithms 253
case study: Payroll Problem with Functions 253
A Reminder about Identifier Scope 261
Adding Data Flow Information to Structure Charts 261
Commentary—The Software DevelopmentMethod 262
Checking the Correctness of an Algorithm 263
Nested if Statements and Multiple-Alternative Decisions 265
Comparison of Nested if Statements and a Sequenceof if Statements 266
Writing a Nested if as a Multiple-AlternativeDecision 266
Order of Conditions 268
Short-Circuit Evaluation of Logical Expressions 271
The switch Control Statement 273
Proper Use of break 276
Comparison of Nested if Statements and the switch
Statement 276
Using a switch Statement to Select Alternative
Functions 276
4.9 Common Programming Errors 278
Chapter Review 279
Quick-Check Exercises 282
Review Questions 284
Programming Projects 285
Answers to Quick-Check Exercises 290
4.4
4.5
4.6
4.7
22 Contents
chapter five Repetition and Loop Statements 293
5.1 Counting Loops and the while Statement 294
The while Statement 295
Syntax of the while Statement 296
5.2 Accumulating a Sum or Product in a Loop 299
Multiplying a List of Numbers 302
Compound Assignment Operators 303
5.3 The for Statement 305
Increment and Decrement Operators 307
Increments and Decrements Other than One 309
Displaying a Table of Values 310
5.4 Conditional Loops 313
A Loop with a Decreasing Loop Control
Variable 314
case STUDY: Monitoring Oil Supply 314
Zero Iteration Loops 316
More General Conditional Loops 318
5.5 Loop Design and Loop Patterns 320
Sentinel-Controlled Loops 321
Calculating an Average 324
Flag-Controlled Loops 325
5.6 The do-while Statement 327
5.7 Review of while, for, and do-while Loops 333
5.8 Nested Loops 335
5.9 Debugging and Testing Programs 340
Using a Debugger 340
Debugging without a Debugger 341
Off-by-One Errors 342
Testing 343
5.10 Loops in Graphics Programs (Optional) 343
Animation 346
5.11 Common Programming Errors 350
Chapter Review 353
Quick-Check Exercises 355
Review Questions 356
Programming Projects 358
Graphics Projects 364
Answers to Quick-Check Exercises 364
Mike Weisert 365
Contents 23
chapter six Modular Programming 367
6.1 Value and Reference Parameters 368
Call-by-Value and Call-by-Reference Parameters 370
void Functions Can Return Results 372
When to Use a Reference or a Value Parameter 372
Comparison of Value and Reference Parameters 373
Protection Afforded by Value Parameters 373
Argument/Parameter List CorrespondenceRevisited 374
6.2 Functions with Output and Input Parameters 378
6.3 Stepwise Design with Function 385
case study: General Sum and Average Problem 386
Multiple Declarations of Identifiers in a
Program 393
6.4 Using Objects with Functions 395
6.5 Debugging and Testing a Program System 397
Top-Down Testing and Stubs 397
Bottom-Up Testing and Drivers 398
Debugging Tips for Program Systems 399
Identifier Scope and Watch Window Variables 400
Black-Box versus White-Box Testing 400
6.6 Recursive Functions (Optional) 402
6.7 Common Programming Errors 405
Chapter Review 406
Quick-Check Exercises 408
Review Questions 409
Programming Projects 410
Answers to Quick-Check Exercises 418
Robert Sebesta 419
chapter seven Simple Data Types 421
7.1 Constants Revisited 422
The #define Compiler Directive 422
7.2 Internal Representations of Numeric Data Types 423
Fixed-Point and Floating-Point Data Types 423
Integer Types 424
Floating-Point Types 425
Types of Numeric Literals 425
24 Contents
Value Ranges for Integer and Floating-Point Types 425
Numerical Inaccuracies 425
Mixing Types: Promotions 427
Type Conversions 427
Type Casting 428
7.3 Character Data and Functions 430
Some Useful Character Functions 431
7.4 Type bool Data and Logical Expressions 435
Complementing Logical Expressions 435
Type bool Functions 437
Input and Output of Type bool Data 437
7.5 Enumeration Types 439
Characters as Enumerator Values 441
Comparisons Involving Enumeration Types 442
Distinctions among Integral Types 442
Reading and Writing Enumeration Type Values 442
Placement of Enumeration Type Declarations 445
Enumeration Types as Cast Operators 445
7.6 Iterative Approximations 448
Function Parameters 449
case study: Bisection Method for Finding Roots 450
7.7 Using Type char Data to Control a Graphics Program(Optional) 456
Generating Random Numbers 459
Seeding the Random Number Generator 460
7.8 Common Programming Errors 461
Chapter Review 463
Quick-Check Exercises 464
Review Questions 465
Programming Projects 466
Graphics Projects 475
Answers to Quick-Check Exercises 475
jhapter eight Streams and Files 477
8.1 The Standard Input/Output Streams 477
Reading One Character at a Time 482
8.2 External Files 486
Interactive versus Batch Processing 486
Directory Names for External Files 487
Attaching Streams to External Files 487
Contents 25
Function copyLine 491
More on the Newline Character 491
Using getline with a File Stream 493
8.3 Using External Files for Communication between
Programs 495
case study: Preparing a Payroll File 495
8.4 More on Reading String Data 501
Using ignore to Advance Past the Newline
Character 502
8.5 Input/Output Manipulators 504
8.6 Common Programrning Errors 507
Chapter Review 508
Quick-Check Exercises 510
Review Questions 510
Programming Projects 511
Answers to Quick-Check Exercises 518
Anita Borg 519
chapter nine Data Structures:Arrays and Structs 521
9.1 The Array Data Type 522
Array Declaration 522
Array Initialization 525
Array Subscripts 526
9.2 Sequential Access to Array Elements 529
Strings and Arrays of Characters 532
9.3 Array Arguments 534
Array Elements as Arguments 535
Passing an Array Argument 536
9.4 Reading Part of an Array 541
9.5 Searching and Sorting Arrays 544
Finding the Smallest Value in an Array 544
Array Search 546
Sorting an Array in Ascending Order 547
9.6 Analyzing Algorithms: Big-0 Notation 551
Analysis of a Search Algorithm 551
Analysis of a Sort Algorithm 552
9.7 Multidimensional Arrays 554
Declaring Two-Dimensional Arrays 554
Initializing Two-Dimensional Arrays 556
26 Contents
Nested Loops for Processing Two-Dimensional
Arrays 556
Two-Dimensional Arrays as Function
Arguments 557
Arrays with Several Dimensions 558
9.8 The Struct Data Type 560
Declaring a Struct Type and Struct Variables 561
Accessing Members of a Struct 563
9.9 Structs as Operands and Arguments 564
Struct Copy or Assignment 564
Passing a Struct as an Argument 564
Reading a Struct 566
A Struct as a Function Result 567
Efficiency of Reference Arguments 567
9.10 Arrays of Structs 569
9.11 Strings as Arrays of Characters (Optional) 572
Declaring and Initializing an Array of Characters 572
Reading and Writing Character Arrays 573
Some Useful Functions for Character Arrays 574
9.12 Graphics Programs with Arrays (Optional) 576
Drawing a Polygon 576
Drawing a Grid 578
9.13 Common Programming Errors 583
Chapter Review 585
Quick-Check Exercises 586
Review Questions 588
Programming Projects 590
Answers to Quick-Check Exercises 597
chapter ten User-Defined Classes 599
10.1 Class Definition and Use 600
The counter Class 600
Class Definition for the counter Class 601
Compiler Directives in File counter. h 604
Using the counter Class 605
Compiler Directives in File CounterTest. cpp 606
10.2 Class Implementation 607
Constructors 609
Accessor and Modifier Functions 610
Compiler Directives in File counter. cpp 611
Contents 27
10.3 Summary of Rules for Use of Classes and Objects 612
Objects as Class Instances 612
Public versus Private Access 612
Syntax for Class and Member Function Definitions 613
Comparing Structs and Classes 615
Project Files and Separate Compilation 615
Combining Arrays, Structs, and Classes 616
Function Overloading and Polymorphism 616
10.4 Classes as Operands and Arguments 617
10.5 A Fraction Class 619
Design of fraction Class 619
Using Class fraction 621
Implementation File for Class fraction 623
10.6 A Circle Class 627
Design of circle Class 627
Using Class circle 629
Implementation File for Class circle 631
10.7 A Simple String Class 633
Design of Class simpleString 633
Definition of Class simpleString 634
Testing Member Functions of Class simpleString 635
Implementation File for Class simpleString 637
10.8 A Savings Account Class 641
case study: Using the Savings Account Class 641
10.9 Common Programming Errors 648
Chapter Review 650
Quick-Check Exercises 651
Review Questions 652
Programming Projects 653
Answers to Quick-Check Exercises 657
Timothy Budd 659
C h Q pte r el eveII Data Abstraction and Obj ect-Oriented Design 661
11.1 Template Classes 662
Definition of a Template Class 662
Implementation of a Template Class 665
Compiler Instructions to Support SeparateCompilation 668
11.2 The Indexed List Abstract Data type 669
Need for an Indexed List Class 669
28 Contents
Analysis and Design of an Indexed List Class 670
Using the indexList Class 673
11.3 Implementing the Indexed List Class 676
11.4 Illustrating Object-Oriented Design 683
Object-Oriented Design Methodology 683
case study: An Address Bookfor an Email Provider 683
11.5 Operator Overloading and Friends 699
Operator Overloading 699
Friends 701
11.6 The vector Class 703
Vectors and Arrays 705
Vector Functions 705
Accessing a Vector through an Iterator 706
Standard Algorithms 707
Using a vector in the Email Address Book Case
Study 708
11.7 Common Programming Errors 712
Chapter Review 714
Quick-Check Exercises 714
Review Questions 715
Programming Projects 716
Answers to Quick-Check Exercises 721
John Lakos 723
chapter twelve Recursion 725
12.1 The Nature of Recursion 726
Properties of Recursive Problems and Solutions 727
12.2 Tracing Recursive Functions 729
Tracing a Recursive Function 729
Displaying Characters in Reverse Order 730
Stack for Function Calls 733
Implementation of Argument Stacks in C++ 735
12.3 Recursive Mathematical Functions 736
12.4 Recursive Functions with Array Arguments 742
case study: Binary Search 744
12.5 Problem Solving with Recursion 749
case study: The Towers ofHanoi 749
Comparison of Iteration and Recursive
Functions 755
Contents
12.6 Common Programming Errors 755
Chapter Review 757
Quick-Check Exercises 757
Review Questions 757
Programming Projects 758
Answers to Quick-Check Exercises 760
Marshall Cline 761
er thirteen Pointers and Dynamic Data Structures 763
13.1 Pointers and the new Operator 764
Accessing Data with Pointers 765
Pointer Operations 766
Pointers with Arrays 766
Pointers to Structs 767
13.2 Manipulating the Heap 771
Effect of the new Operator on the Heap 771
Returning Cells to the Heap 772
13.3 Linked Lists and the list Class 773
Declaring Nodes 773
Connecting Nodes 774
Inserting a Node in a List 775
Insertion at the Head of a List 776
Insertion at the End of a List 777
Deleting a Node 778
Traversing a List 778
Circular Lists and Two-Way Lists (Optional)The list Class 781
13.4 The Stack Abstract Data Type 784
The C++ stack Class 785
Implementing a stack Template Class 789
Implementing the Stack Operators 789
Testing the Stack ADT 792
13.5 The Queue Abstract Data Type 794
The C++ queue Class 795
Implementing a Queue ADT 795
13.6 Binary Trees 801
Binary Search Tree 802
Searching a Binary Search Tree 802
Building a Binary Search Tree 804
Displaying a Binary Search Tree 805
30 Contents
13.7 Binary Search Tree Abstract Data Type 807
Design of Binary Tree Class 807
Implementation of Binary Tree Class 810
13.8 Efficiency of a Binary Search Tree 815
13.9 Common Programming Errors 817
Syntax Errors 817
Run-Time Errors 817
Chapter Review 818
Quick-Check Exercises 819
Review Questions 821
Programming Projects 823
Answers to Quick-Check Exercises 827
chapter fourteen Multiprocessing Using Processes and Threads 829
14.1 Multitasking 830
Linear versus Parallel Programming 830
Multitasking as Time Sharing 831
Preemptive Multitasking 832
Time Slices and Parallelism 832
Concurrent Programming 834
14.2 Processes 835
Creating a Process 836
Waiting for a Process 838
Executing Another Program from a Process 840
14.3 Interprocess Communications and Pipes 842
Pipes 842
Using Pipes 844
Interprocess Communications Using Standard
Input 846
Illustrating Communication between a Parentand a Child Process 847
14.4 Threads 851
Creating a Thread 852
Thread Synchronization 855
Mutual Exclusion Locking 856
Deadlocks 859
case study: Threads Illustrated 863
14.5 Common Programming Errors 877
Chapter Review 877
Review of C++ Constructs 878
Contents
Quick-Check Exercises 880
Review Questions 881
Programming Projects 881
Answers to Quick-Check Exercises
Index 885
The following are available online:
Append iX A ASCII Character Set
Appendix B Reserved Words and Special Characters
Appendix C Selected C++ Library Facilities
Appendix D Operators
AppendiX E A Brief Introduction to Inheritance
and Polymorphism
E.l Subclassing for Specialization
E.2 Subclassing for SpecificationCASE study: Areas and Perimeters
of Different Figures
E.3 Commentary
E.4 Polymorphism
Answers to Odd-Numbered Questions