+ All Categories
Home > Documents > PROBLEM SOLVING - GBV

PROBLEM SOLVING - GBV

Date post: 07-Apr-2022
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
16
PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London Toronto Sydney Tokyo Singapore Madrid Mexico City Munich Paris Cape Town Hong Kong Montreal
Transcript

PROBLEM SOLVING

W I T H

S E V E N T H E D I T I O N

WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN D I E G O

CONTRIBUTOR

KENRICK MOCK

UNIVERSITY OF ALASKA, A N C H O R A G E

PEARSON

Addison Wesley

Boston San Francisco New York London Toronto Sydney Tokyo Singapore Madrid

Mexico City Munich Paris Cape Town Hong Kong Montreal

Contents

TABLE OF LOCATION OF VIDEO NOTES

Inside front cover

C h a p t e r 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 47 The Software Life Cycle 47

1.3 INTRODUCTION TO C++ 49 Origins of the C++ Language 49 A Sample C++ Program 50 Pitfall: Using the Wrong Slash in \n 54 Programming Tip: Input and Output Syntax 54 Layout of a Simple C++ Program 54 Pitfall: Putting a Space before the include File Name 56 Compiling and Running a C++ Program 57 Programming Tip: Getting Your Program to Run 57

1.4 TESTING AND DEBUGGING 60 Kinds of Program Errors 60 Pitfall: Assuming Your Program Is Correct 61

15

16 CONTENTS

Chapter Summary 62

Answers to Self-Test Exercises 63

Programming Projects 66

C h a p t e r 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 ein 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

The Type char 93

The Type boo I 94

Introduction to the Class string 95 Type Compatibilities 96 Arithmetic Operators and Expressions 99 Pitfall: Whole Numbers in Division 101 More Assignment Statements 103

2.4 SIMPLE FLOW OF CONTROL 104 A Simple Branching Mechanism 104 Pitfall: Strings of Inequalities 110 Pitfall: Using = in place of == 111 Compound Statements 112 Simple Loop Mechanisms 114

Increment and Decrement Operators 117

Programming Example: ChargeCard Balance 119

Pitfall: Infinite Loops 120

2.5 PROGRAM STYLE 123 Indenting 123 Comments 124 Naming Constants 126

Chapter Summary 128

Answers to Self-Test Exercises 129

Programming Projects 134

C h a p t e r 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 1.51 Multiway if-else Statements 153 Programming Example: State Income Tax 155

The switch Statement 159 Pitfall: Forgetting a break in a switch Statement 163 Using switch Statements for Menus 164 Blocks 164 Pitfall: Inadvertent Local Variables 169

3.3 MORE ABOUT C++ LOOP STATEMENTS 170 The while Statements Reviewed 171 Increment and Decrement Operators Revisited 172 The for Statement 175 Pitfall: Extra Semicolon in a for Statement 180 What Kind of Loop to Use 181 Pitfall: Uninitialized Variables and Infinite Loops 183 The break Statement 183 Pitfall: The break Statement in Nested Loops 185

18 CONTENTS

3.4 DESIGNING LOOPS 186 Loops for Sums and Products 186 Ending a Loop 187 Nested Loops 191 Debugging Loops 193

Chapter Summary 196

Answers to Self-Test Exercises 197

Programming Projects 203

C h a p t e r 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 Type Casting 218 Older Form of Type Casting 220 Pitfall: Integer Division Drops the Fractional Part 221

4.3 PROGRAMMER-DEFINED FUNCTIONS 222 Function Definitions 222 Functions That Return a Boolean Value 226 Alternate Form for Function Declarations 229 Pitfall: Arguments in the Wrong Order 229 Function Definition-Syntax Summary 231 More About Placement of Function Definitions 232 Programming Tip: Use Function Calls in Branching Statements 232

4.4 PROCEDURAL ABSTRACTION 234 The Black Box Analogy 234 Programming Tip: Choosing Formal Parameter Names 236 Programming Tip: Nested Loops 238 Case Study: Buying Pizza 241 Programming Tip: Use Pseudocode 247

4.5 LOCAL VARIABLES 248 The Small Program Analogy 248 Programming Example: Experimental Pea Patch 250 Global Constants and Global Variables 251

Call-by-Value Formal Parameters Are Local Variables 254 Namespaces Revisited 256 Programming Example: The Factorial Function 259

4.6 OVERLOADING FUNCTION NAMES 260 Introduction to Overloading 261 Programming Example: Revised Pizza-Buying Program 263 Automatic Type Conversion 266

Chapter Summary 269

Answers to Self-Test Exercises 269

Programming Projects 274

C h a p t e r 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 296

Mixed Parameter Lists 298 Programming Tip: What Kind of Parameter to Use 298 Pitfall: Inadvertent Local Variables 300

5.3 USING PROCEDURAL ABSTRACTION 302 Functions Calling Functions 303 Preconditions and Postconditions 303 Case Study: Supermarket Pricing 304

5.4 TESTING AND DEBUGGING FUNCTIONS 312 Stubs and Drivers 312

5.5 GENERAL DEBUGGING TECHNIQUES 317 Keep an Open Mind 317 Check Common Errors 318 Localize the Error 318 The assert macro 321

Chapter Summary 322

Answers to Self-Test Exercises 323

Programming Projects 327

C h a p t e r 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 343 Techniques for File I/O 346 Appending to a File (Optional) 350 File Names as Input (Optional) 350

6.2 TOOLS FOR STREAM I/O 353 Formatting Output with Stream Functions 353 Manipulators 358 Streams as Arguments to Functions 362 Programming Tip: Checking for the End of a File 362 A Note on Namespaces 366 Programming Example: Cleaning Up a File Format 367

6.3 CHARACTER I/O 368 The Member Functions get and put 369 The putback Member Function (Optional) 372 Programming Example: Checking Input 373 Pitfall: Unexpected ' \ n ' in Input 376 The eof Member Function 379 Programming Example: Editing a Text File 382 Predefined Character Functions 382 Pitfall: toupper and tolower Return Values 385

Chapter Summary 387

Answers to Self-Test Exercises 389

Programming Projects 394

C h a p t e r 7 Arrays 405

7.1 INTRODUCTION TO ARRAYS 406 Declaring and Referencing Arrays 406 Programming Tip: Use for Loops with Arrays 408 Pitfall: Array Indexes Always Start with Zero 408 Programming Tip: Use a Defined Constant for the Size of an Array Arrays in Memory 410 Pitfall: Array Index Out of Range 411 Initializing Arrays 413

7.2 ARRAYS IN FUNCTIONS 415 Indexed Variables as Function Arguments 415 Entire Arrays as Function Arguments 418 The const Parameter Modifier 421 Pitfall: Inconsistent Use of const Parameters 423 Functions That Return an Array 424 Case Study: Production Graph 424

7.3 PROGRAMMING WITH ARRAYS 438 Partially Filled Arrays 438 Programming Tip: Do Not Skimp on Formal Parameters 441 Programming Example: Searching an Array 442 Programming Example: Sorting an Array 444

7.4 MULTIDIMENSIONAL ARRAYS 449 Multidimensional Array Basics 450 Multidimensional Array Parameters 450 Programming Example: Two-Dimensional Grading Program 452 Pitfall: Using Commas Between Array Indexes 457

Chapter Summary 457 Answers to Self-Test Exercises 458 Programming Projects 463

C h a p t e r 8 Strings and Vectors 475

8.1 AN ARRAY TYPE FOR STRINGS 477 C-String Values and C-String Variables 477 Pitfall: Using = and == with С Strings 481

Other Functions in <cstring> 483 C-String Input and Output 487 C-String-to-Number Conversions and Robust Input 490

8.2 THE STANDARD s t r i n g CLASS 495 Introduction to the Standard Class s t r ing 495 I/O with the Class st r ing 498 Programming Tip: More Versions of get l ine 502 Pitfall: Mixing ein » var iable; and get l ine 502 String Processing with the Class st r ing 504 Programming Example: Palindrome Testing 506 Converting between st r ing Objects and С Strings 511

8.3 VECTORS 512 Vector Basics 512 Pitfall: Using Square Brackets Beyond the Vector Size 514 Programming Tip: Vector Assignment Is Well Behaved 516 Efficiency Issues 517

Chapter Summary 518 Answers to Self-Test Exercises 519 Programming Projects 521

C h a p t e r 9 Pointers and Dynamic Arrays 529

9.1 POINTERS 530 Pointer Variables 531 Basic Memory Management 538 Pitfall: Dangling Pointers 539 Static Variables and Automatic Variables 540 Programming Tip: Define Pointer Types 540

9.2 DYNAMIC ARRAYS 543 Array Variables and Pointer Variables 543 Creating and Using Dynamic Arrays 543 Pointer Arithmetic (Optional) 549 Multidimensional Dynamic Arrays (Optional) 551

Chapter Summary 553 Answers to Self-Test Exercises 553 Programming Projects 554

C h a p t e r 1 0 Def in ing Classes 559

10.1 STRUCTURES 560 Structures for Diverse Data 560 Pitfall: Forgetting a Semicolon in a Structure Definition 565 Structures as Function Arguments 566 Programming Tip: Use Hierarchical Structures 567 Initializing Structures 569

10.2 CLASSES 572 Defining Classes and Member Functions 572 Public and Private Members 577 Programming Tip: Make All Member Variables Private 585 Programming Tip: Define Accessor and Mutator Functions 585 Programming Tip: Use the Assignment Operator with Objects 587 Programming Example: BankAccount Class—Version 1 587 Summary of Some Properties of Classes 592 Constructors for Initialization 594 Programming Tip: Always Include a Default Constructor 602 Pitfall: Constructors with No Arguments 603

10.3 ABSTRACT DATA TYPES 605 Classes to Produce Abstract Data Types 606 Programming Example: Alternative Implementation of a Class 610

10.4 INTRODUCTION TO INHERITANCE 614 Inheritance Among Stream Classes 615 Programming Example: Another new.line Function 618 Default Arguments for Functions (Optional) 619 Defining Derived Classes 621

Chapter Summary 624

Answers to Self-Test Exercises 625

Programming Projects 633

C h a p t e r 1 1 Friends, Overloaded Operators, and Arrays in Classes 639

11.1 FRIEND FUNCTIONS 640 Programming Example: An Equality Function 640

Friend Functions 644

24 CONTENTS

Programming Tip: Define Both Accessor Functions and Friend Functions 646

Programming Tip: Use Both Member and Nonmember Functions 648 Programming Example: Money Class (Version 1) 648 Implementation of digi.t_to_i.nt (Optional) 655 Pitfall: Leading Zeros in Number Constants 656 The const Parameter Modifier 658 Pitfall: Inconsistent Use of const 660

11.2 OVERLOADING OPERATORS 663 Overloading Operators 664 Constructors for Automatic Type Conversion 668 Overloading Unary Operators 670 Overloading » and « 670

11.3 ARRAYS AND CLASSES 681 Arrays of Classes 681 Arrays as Class Members 685 Programming Example: A Class for a Partially Filled Array 686

11.4 CLASSES AND DYNAMIC ARRAYS 689 Programming Example: A String Variable Class 689

Destructors 693 Pitfall: Pointers as Call-by-Value Parameters 695 Copy Constructors 697 Overloading the Assignment Operator 702

Chapter Summary 705

Answers to Self-Test Exercises 706

Programming Projects 716

C h a p t e r 1 2 Separate Compilation and Namespaces 725

12.1 SEPARATE COMPILATION 726 ADTs Reviewed 727 Case Study: DigitalTime—A Class Compiled Separately 728 Using #ifndef 737 Programming Tip: Defining Other Libraries 740

12.2 NAMESPACES 742 Namespaces and using Directives 742 Creating a Namespace 744 Qualifying Names 747 A Subtle Point About Namespaces (Optional) 748 Unnamed Namespaces 749 Programming Tip: Choosing a Name for a Namespace 752 Pitfall: Confusing the Global Namespace and the Unnamed

Namespace 754

Chapter Summary 757

Answers to Self-Test Exercises 757

Programming Projects 759

C h a p t e r 1 3 Pointers and Linked Lists 763

13.1 NODES AND LINKED LISTS 764 Nodes 764 Linked Lists 770 Inserting a Node at the Head of a List 771 Pitfall: Losing Nodes 774 Searching a Linked List 775 Pointers as Iterators 779 Inserting and Removing Nodes Inside a List 779 Pitfall: Using the Assignment Operator with Dynamic

Data Structures 782 Variations on Linked Lists 784 Linked Lists of Classes 786

13.2 STACKS AND QUEUES 790 Stacks 790 Programming Example: A Stack Class 791 Queues 796 Programming Example: A Queue Class 797

Chapter Summary 801

Answers to Self-Test Exercises 802

Programming Projects 805

C h a p t e r 1 4 Recursion 811

14.1 RECURSIVE FUNCTIONS FOR TASKS 813 Case Study: Vertical Numbers 813 A Closer Look at Recursion 820 Pitfall: Infinite Recursion 821 Stacks for Recursion 823 Pitfall: Stack Overflow 824 Recursion Versus Iteration 825

14.2 RECURSIVE FUNCTIONS FOR VALUES 826 General Form for a Recursive Function That Returns a Value 826 Programming Example: Another Powers Function 827

14.3 THINKING RECURSIVELY 831 Recursive Design Techniques 831 Case Study: Binary Search—An Example of Recursive Thinking 833 Programming Example: A Recursive Member Function 840

Chapter Summary 845

Answers to Self-Test Exercises 845

Programming Projects 850

C h a p t e r 1 5 Inheritance 855

15.1 INHERITANCE BASICS 856 Derived Classes 857 Constructors in Derived Classes 865 Pitfall: Use of Private Member Variables from the Base Class 868 Pitfall: Private Member Functions Are Effectively Not Inherited 870 The protected Qualifier 870 Redefinition of Member Functions 873 Redefining Versus Overloading 877 Access to a Redefined Base Function 878

15.2 INHERITANCE DETAILS 879 Functions That Are Not Inherited 880 Assignment Operators and Copy Constructors in Derived Classes 880 Destructors in Derived Classes 881

15.3 POLYMORPHISM 883 Late Binding 883 Virtual Functions in C++ 884 Virtual Functions and Extended Type Compatibility 890 Pitfall: The Slicing Problem 894 Pitfall: Not Using Virtual Member Functions 894 Pitfall: Attempting to Compile Class Definitions Without Definitions for

Every Virtual Member Function 895 Programming Tip: Make Destructors Virtual 896

Chapter Summary 897

Answers to Self-Test Exercises 898

Programming Projects 902

C h a p t e r 1 6 Exception Handling 911

16.1 EXCEPTION-HANDLING BASICS 913 A Toy Example of Exception Handling 913 Defining Your Own Exception Classes 922 Multiple Throws and Catches 922 Pitfall: Catch the More Specific Exception First 926 Programming Tip: Exception Classes Can Be Trivial 927 Throwing an Exception in a Function 928 Exception Specification 928 Pitfall: Exception Specification in Derived Classes 932

16.2 PROGRAMMING TECHNIQUES FOR EXCEPTION HANDLING 933 When to Throw an Exception 933 Pitfall: Uncaught Exceptions 935 Pitfall: Nested try-catch Blocks 935 Pitfall: Overuse of Exceptions 935 Exception Class Hierarchies 936 Testing for Available Memory 936 Rethrowing an Exception 937

Chapter Summary 937

Answers to Self-Test Exercises 937

Programming Projects 939

C h a p t e r 1 7 Templates 943

17.1 TEMPLATES FOR ALGORITHM ABSTRACTION 944 Templates for Functions 945 Pitfall: Compiler Complications 949 Programming Example: A Generic Sorting Function 951

Programming Tip: How to Define Templates 955 Pitfall: Using a Template with an Inappropriate Type 956

17.2 TEMPLATES FOR DATA ABSTRACTION 957 Syntax for Class Templates 957 Programming Example: An Array Class 960

Chapter Summary 966

Answers to Self-Test Exercises 966

Programming Projects 969

C h a p t e r 1 8 Standard Template Library 973

18.1 ITERATORS 975 using Declarations 975 Iterator Basics 976 Pitfall: Compiler Problems 981 Kinds of Iterators 982 Constant and Mutable Iterators 986 Reverse Iterators 987 Other Kinds of Iterators 989

18.2 CONTAINERS 990 Sequential Containers 990 Pitfall: Iterators and Removing Elements 995 Programming Tip: Type Definitions in Containers 995 Container Adapters stack and queue 996 Associative Containers set and map 1000 Efficiency 1006

18.3 GENERIC ALGORITHMS 1007 Running Times and Big-0 Notation 1008 Container Access Running Times 1012 Nonmodifying Sequence Algorithms 1013 Container Modifying Algorithms 1019

CONTENTS 29

Set Algorithms 1019 Sorting Algorithms 1021

Chapter Summary 1021 Answers to Self-Test Exercises 1022 Programming Projects 1024

APPENDICES 1 C++ Keywords 1029 2 Precedence of Operators 1030 3 The ASCII Character Set 1032 4 Some Library Functions 1033 5 Inline Functions 1041 6 Overloading the Array Index Square Brackets 1042 7 The this Pointer 1044 8 Overloading Operators as Member Operators 1047

INDEX 1049


Recommended