Starting Out with C++ From Control Structures through Objects, Brief Version 9th Edition.pdf
Document Details
Uploaded by Deleted User
Full Transcript
Starting Out With C++ From Control Structures through Objects Brief Version Ninth Edition Starting Out With C++ From Control Structures through Objects Brief Version Ninth Edition Tony Gaddis Haywood Community College 330 Hudson Street, New York, NY 10013 Senior Vice President Courseware...
Starting Out With C++ From Control Structures through Objects Brief Version Ninth Edition Starting Out With C++ From Control Structures through Objects Brief Version Ninth Edition Tony Gaddis Haywood Community College 330 Hudson Street, New York, NY 10013 Senior Vice President Courseware Portfolio Management: Marcia J. Horton Director, Portfolio Management: Engineering, Computer Science & Global Editions: Julian Partridge Portfolio Manager: Matt Goldstein Portfolio Management Assistant: Meghan Jacoby Field Marketing Manager: Demetrius Hall Product Marketing Manager: Yvonne Vannatta Marketing Assistant: Jon Bryant Managing Producer, ECS and Math: Scott Disanno Content Producer: Amanda Brands Composition: SPi Global Project Manager: Billu Suresh/ SPi Global Cover Designer: Joyce Wells Cover Image: Viktar Malyshchyts/123RF Printer/Binder: LSC Communications, Inc. Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear on the Credits page in the endmatter of this textbook. Copyright © 2019, 2016, 2012 Pearson Education, Inc. Hoboken, NJ 07030. All rights reserved. Manufactured in the United States of America. This publication is protected by copyright and permissions should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise. For information regarding permissions, request forms and the appropriate contacts within the Pearson Education Global Rights & Permissions department, please visit www.pearsoned.com/permissions/. Many of the designations by manufacturers and seller to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps. The author and publisher of this book have used their best efforts in preparing this book. These efforts include the development, research, and testing of theories and programs to determine their effectiveness. The author and publisher make no warranty of any kind, expressed or implied, with regard to these programs or the documentation contained in this book. The author and publisher shall not be liable in any event for incidental or consequential damages with, or arising out of, the furnishing, performance, or use of these programs. Library of Congress Cataloging-in-Publication Data Names: Gaddis, Tony, author. Title: Starting out with C++. From control structures through objects / Tony Gaddis, Haywood Community College. Description: Brief version, Ninth edition. | New York : Pearson Education, Identifiers: LCCN 2017059120| ISBN 9780134895734 | ISBN 0134895738 Subjects: LCSH: C++ (Computer program language) Classification: LCC QA76.73.C153 G3342 2019 | DDC 005.13/3—dc23 LC record available at https://lccn.loc.gov/2017059120 1 18 ISBN-13: 978-0-13-489573-4 ISBN-10: 0-13-489573-8 Contents at a Glance 1. Preface xv 1. CHAPTER 1 Introduction to Computers and Programming 1 2. CHAPTER 2 Introduction to C++ 27 3. CHAPTER 3 Expressions and Interactivity 85 4. CHAPTER 4 Making Decisions 151 5. CHAPTER 5 Loops and Files 231 6. CHAPTER 6 Functions 305 7. CHAPTER 7 Arrays and Vectors 381 8. CHAPTER 8 Searching and Sorting Arrays 463 9. CHAPTER 9 Pointers 503 10. CHAPTER 10 Characters, C-Strings, and More about the string Class 557 11. CHAPTER 11 Structured Data 613 12. CHAPTER 12 Advanced File Operations 665 13. CHAPTER 13 Introduction to Classes 719 14. CHAPTER 14 More about Classes 817 15. CHAPTER 15 Inheritance, Polymorphism, and Virtual Functions 907 1. Appendix A: The ASCII Character Set 989 2. Appendix B: Operator Precedence and Associativity 991 3. Quick References 993 4. Index 995 Online The following appendices are available at www.pearson.com/gaddis. 1. Appendix C: Introduction to Flowcharting 2. Appendix D: Using UML in Class Design 3. Appendix E: Namespaces 4. Appendix F: Passing Command Line Arguments 5. Appendix G: Binary Numbers and Bitwise Operations 6. Appendix H: STL Algorithms 7. Appendix I: Multi-Source File Programs 8. Appendix J: Stream Member Functions for Formatting 9. Appendix K: Unions 10. Appendix L: Answers to Checkpoints 11. Appendix M: Answers to Odd Numbered Review Questions 12. Case Study 1: String Manipulation 13. Case Study 2: High Adventure Travel Agency—Part 1 14. Case Study 3: Loan Amortization 15. Case Study 4: Creating a String Class 16. Case Study 5: High Adventure Travel Agency—Part 2 17. Case Study 6: High Adventure Travel Agency—Part 3 18. Case Study 7: Intersection of Sets 19. Case Study 8: Sales Commission Contents 1. Preface xv 1. CHAPTER 1 Introduction to Computers and Programming 1 1. 1.1 Why Program?1 2. 1.2 Computer Systems: Hardware and Software 2 3. 1.3 Programs and Programming Languages 8 4. 1.4 What Is a Program Made of? 14 5. 1.5 Input, Processing, and Output 17 6. 1.6 The Programming Process 18 7. 1.7 Procedural and Object-Oriented Programming 22 1. Review Questions and Exercises 24 2. CHAPTER 2 Introduction to C++ 27 1. 2.1 The Parts of a C++ Program 27 2. 2.2 The cout Object 31 3. 2.3 The #include Directive 36 4. 2.4 Variables, Literals, and Assignment Statements 38 5. 2.5 Identifiers 42 6. 2.6 Integer Data Types 43 7. 2.7 The char Data Type 49 8. 2.8 The C++ string Class 53 9. 2.9 Floating-Point Data Types 55 10. 2.10 The bool Data Type 58 11. 2.11 Determining the Size of a Data Type 59 12. 2.12 More about Variable Assignments and Initialization 60 13. 2.13 Scope 62 14. 2.14 Arithmetic Operators 63 15. 2.15 Comments 71 16. 2.16 Named Constants 73 17. 2.17 Programming Style 75 1. Review Questions and Exercises 77 2. Programming Challenges 81 3. CHAPTER 3 Expressions and Interactivity 85 1. 3.1 The cin Object 85 2. 3.2 Mathematical Expressions 91 3. 3.3 When You Mix Apples and Oranges: Type Conversion 100 4. 3.4 Overflow and Underflow 102 5. 3.5 Type Casting 103 6. 3.6 Multiple Assignment and Combined Assignment 106 7. 3.7 Formatting Output 110 8. 3.8 Working with Characters and string Objects 120 9. 3.9 More Mathematical Library Functions 126 10. 3.10 Focus on Debugging: Hand Tracing a Program 132 11. 3.11 Focus on Problem Solving: A Case Study 134 1. Review Questions and Exercises 138 2. Programming Challenges 144 4. CHAPTER 4 Making Decisions 151 1. 4.1 Relational Operators 151 2. 4.2 The if Statement 156 3. 4.3 Expanding the if Statement 164 4. 4.4 The if/else Statement 168 5. 4.5 Nested if Statements 171 6. 4.6 The if/else if Statement 178 7. 4.7 Flags 183 8. 4.8 Logical Operators 184 9. 4.9 Checking Numeric Ranges with Logical Operators 191 10. 4.10 Menus 192 11. 4.11 Focus on Software Engineering: Validating User Input 195 12. 4.12 Comparing Characters and Strings 197 13. 4.13 The Conditional Operator 201 14. 4.14 The switch Statement 204 15. 4.15 More about Blocks and Variable Scope 213 1. Review Questions and Exercises 216 2. Programming Challenges 222 5. CHAPTER 5 Loops and Files 231 1. 5.1 The Increment and Decrement Operators 231 2. 5.2 Introduction to Loops: The while Loop 236 3. 5.3 Using the while Loop for Input Validation 243 4. 5.4 Counters 245 5. 5.5 The do-while Loop 246 6. 5.6 The for Loop 251 7. 5.7 Keeping a Running Total 261 8. 5.8 Sentinels 264 9. 5.9 Focus on Software Engineering: Deciding Which Loop to Use 265 10. 5.10 Nested Loops 266 11. 5.11 Using Files for Data Storage 269 12. 5.12 Optional Topics: Breaking and Continuing a Loop 288 1. Review Questions and Exercises 292 2. Programming Challenges 297 6. CHAPTER 6 Functions 305 1. 6.1 Focus on Software Engineering: Modular Programming 305 2. 6.2 Defining and Calling Functions 306 3. 6.3 Function Prototypes 315 4. 6.4 Sending Data into a Function 317 5. 6.5 Passing Data by Value 322 6. 6.6 Focus on Software Engineering: Using Functions in a Menu- Driven Program 324 7. 6.7 The return Statement 328 8. 6.8 Returning a Value from a Function 330 9. 6.9 Returning a Boolean Value 338 10. 6.10 Local and Global Variables 340 11. 6.11 Static Local Variables 348 12. 6.12 Default Arguments 351 13. 6.13 Using Reference Variables as Parameters 354 14. 6.14 Overloading Functions 360 15. 6.15 The exit() Function 364 16. 6.16 Stubs and Drivers 367 1. Review Questions and Exercises 369 2. Programming Challenges 372 7. CHAPTER 7 Arrays and Vectors 381 1. 7.1 Arrays Hold Multiple Values 381 2. 7.2 Accessing Array Elements 383 3. 7.3 No Bounds Checking in C++ 395 4. 7.4 The Range-Based for Loop 398 5. 7.5 Processing Array Contents 402 6. 7.6 Focus on Software Engineering: Using Parallel Arrays 410 7. 7.7 Arrays as Function Arguments 413 8. 7.8 Two-Dimensional Arrays 424 9. 7.9 Arrays with Three or More Dimensions 431 10. 7.10 Focus on Problem Solving and Program Design: A Case Study 433 11. 7.11 Introduction to the STL vector 435 1. Review Questions and Exercises 449 2. Programming Challenges 454 8. CHAPTER 8 Searching and Sorting Arrays 463 1. 8.1 Focus on Software Engineering: Introduction to Search Algorithms 463 2. 8.2 Focus on Problem Solving and Program Design: A Case Study 469 3. 8.3 Focus on Software Engineering: Introduction to Sorting Algorithms 476 4. 8.4 Focus on Problem Solving and Program Design: A Case Study 486 5. 8.5 Sorting and Searching vectors 495 1. Review Questions and Exercises 498 2. Programming Challenges 499 9. CHAPTER 9 Pointers 503 1. 9.1 Getting the Address of a Variable 503 2. 9.2 Pointer Variables 505 3. 9.3 The Relationship between Arrays and Pointers 512 4. 9.4 Pointer Arithmetic 516 5. 9.5 Initializing Pointers 518 6. 9.6 Comparing Pointers 519 7. 9.7 Pointers as Function Parameters 521 8. 9.8 Dynamic Memory Allocation 530 9. 9.9 Returning Pointers from Functions 534 10. 9.10 Using Smart Pointers to Avoid Memory Leaks 541 11. 9.11 Focus on Problem Solving and Program Design: A Case Study 544 1. Review Questions and Exercises 550 2. Programming Challenges 553 10. CHAPTER 10 Characters, C-Strings, and More about the string Class 557 1. 10.1 Character Testing 557 2. 10.2 Character Case Conversion 561 3. 10.3 C-Strings 564 4. 10.4 Library Functions for Working with C-Strings 568 5. 10.5 String/Numeric Conversion Functions 579 6. 10.6 Focus on Software Engineering: Writing Your Own C-String- Handling Functions 585 7. 10.7 More about the C++ string Class 591 8. 10.8 Focus on Problem Solving and Program Design: A Case Study 603 1. Review Questions and Exercises 604 2. Programming Challenges 607 11. CHAPTER 11 Structured Data 613 1. 11.1 Abstract Data Types 613 2. 11.2 Structures 615 3. 11.3 Accessing Structure Members 618 4. 11.4 Initializing a Structure 622 5. 11.5 Arrays of Structures 625 6. 11.6 Focus on Software Engineering: Nested Structures 627 7. 11.7 Structures as Function Arguments 631 8. 11.8 Returning a Structure from a Function 634 9. 11.9 Pointers to Structures 637 10. 11.10 Focus on Software Engineering: When to Use., When to Use −>, and When to Use * 640 11. 11.11 Enumerated Data Types 642 1. Review Questions and Exercises 653 2. Programming Challenges 659 12. CHAPTER 12 Advanced File Operations 665 1. 12.1 File Operations 665 2. 12.2 File Output Formatting 671 3. 12.3 Passing File Stream Objects to Functions 673 4. 12.4 More Detailed Error Testing 675 5. 12.5 Member Functions for Reading and Writing Files 678 6. 12.6 Focus on Software Engineering: Working with Multiple Files 686 7. 12.7 Binary Files 688 8. 12.8 Creating Records with Structures 693 9. 12.9 Random-Access Files 697 10. 12.10 Opening a File for Both Input and Output 705 1. Review Questions and Exercises 710 2. Programming Challenges 713 13. CHAPTER 13 Introduction to Classes 719 1. 13.1 Procedural and Object-Oriented Programming 719 2. 13.2 Introduction to Classes 726 3. 13.3 Defining an Instance of a Class 731 4. 13.4 Why Have Private Members? 744 5. 13.5 Focus on Software Engineering: Separating Class Specification from Implementation 745 6. 13.6 Inline Member Functions 751 7. 13.7 Constructors 754 8. 13.8 Passing Arguments to Constructors 759 9. 13.9 Destructors 767 10. 13.10 Overloading Constructors 771 11. 13.11 Private Member Functions 775 12. 13.12 Arrays of Objects 777 13. 13.13 Focus on Problem Solving and Program Design: An OOP Case Study 781 14. 13.14 Focus on Object-Oriented Programming: Simulating Dice with Objects 788 15. 13.15 Focus on Object-Oriented Design: The Unified Modeling Language (UML) 792 16. 13.16 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 794 1. Review Questions and Exercises 803 2. Programming Challenges 808 14. CHAPTER 14 More about Classes 817 1. 14.1 Instance and Static Members 817 2. 14.2 Friends of Classes 825 3. 14.3 Memberwise Assignment 830 4. 14.4 Copy Constructors 831 5. 14.5 Operator Overloading 837 6. 14.6 Object Conversion 864 7. 14.7 Aggregation 866 8. 14.8 Focus on Object-Oriented Design: Class Collaborations 871 9. 14.9 Focus on Object-Oriented Programming: Simulating the Game of Cho-Han 876 10. 14.10 Rvalue References and Move Semantics 886 1. Review Questions and Exercises 895 2. Programming Challenges 900 15. CHAPTER 15 Inheritance, Polymorphism, and Virtual Functions 907 1. 15.1 What Is Inheritance? 907 2. 15.2 Protected Members and Class Access 916 3. 15.3 Constructors and Destructors in Base and Derived Classes 922 4. 15.4 Redefining Base Class Functions 936 5. 15.5 Class Hierarchies 941 6. 15.6 Polymorphism and Virtual Member Functions 947 7. 15.7 Abstract Base Classes and Pure Virtual Functions 963 8. 15.8 Multiple Inheritance 970 1. Review Questions and Exercises 977 2. Programming Challenges 981 1. Appendix A: The ASCII Character Set 989 2. Appendix B: Operator Precedence and Associativity 991 3. Quick References 993 4. Index 995 5. Online The following appendices are available at www.pearson.com/gaddis. 6. Appendix C: Introduction to Flowcharting 7. Appendix D: Using UML in Class Design 8. Appendix E: Namespaces 9. Appendix F: Passing Command Line Arguments 10. Appendix G: Binary Numbers and Bitwise Operations 11. Appendix H: STL Algorithms 12. Appendix I: Multi-Source File Programs 13. Appendix J: Stream Member Functions for Formatting 14. Appendix K: Unions 15. Appendix L: Answers to Checkpoints 16. Appendix M: Answers to Odd Numbered Review Questions 17. Case Study 1: String Manipulation 18. Case Study 2: High Adventure Travel Agency—Part 1 19. Case Study 3: Loan Amortization 20. Case Study 4: Creating a String Class 21. Case Study 5: High Adventure Travel Agency—Part 2 22. Case Study 6: High Adventure Travel Agency—Part 3 23. Case Study 7: Intersection of Sets 24. Case Study 8: Sales Commission Location of Videonotes in the Text 1. Chapter 1 1. Introduction to Flowcharting, p. 20 2. Designing a Program with Pseudocode, p. 20 3. Designing the Account Balance Program, p. 25 4. Predicting the Result of Problem 33, p. 26 2. Chapter 2 1. Using cout, p. 32 2. Variable Definitions, p. 38 3. Assignment Statements and Simple Math Expressions, p. 63 4. Solving the Restaurant Bill Problem, p. 81 3. Chapter 3 1. Reading Input with cin, p. 85 2. Formatting Numbers with setprecision, p. 113 3. Solving the Stadium Seating Problem, p. 144 4. Chapter 4 1. The if Statement, p. 156 2. The if/else statement, p. 168 3. The if/else if Statement, p. 178 4. Solving the Time Calculator Problem, p. 223 5. Chapter 5 1. The while Loop, p. 236 2. The for Loop, p. 251 3. Reading Data from a File, p. 278 4. Solving the Calories Burned Problem, p. 297 6. Chapter 6 1. Functions and Arguments, p. 317 2. Value-Returning Functions, p. 330 3. Solving the Markup Problem, p. 372 7. Chapter 7 1. Accessing Array Elements with a Loop, p. 386 2. Passing an Array to a Function, p. 413 3. Solving the Chips and Salsa Problem, p. 455 8. Chapter 8 1. The Binary Search, p. 466 2. The Selection Sort, p. 482 3. Solving the Charge Account Validation Modification Problem, p. 500 9. Chapter 9 1. Dynamically Allocating an Array, p. 531 2. Solving the Pointer Rewrite Problem, p. 554 10. Chapter 10 1. Writing a C-String-Handling Function, p. 585 2. More About the string Class, p. 591 3. Solving the Backward String Problem, p. 607 11. Chapter 11 1. Creating a Structure, p. 615 2. Passing a Structure to a Function, p. 631 3. Solving the Weather Statistics Problem, p. 659 12. Chapter 12 1. Passing File Stream Objects to Functions, p. 673 2. Working with Multiple Files, p. 686 3. Solving the File Encryption Filter Problem, p. 716 13. Chapter 13 1. Writing a Class, p. 726 2. Defining an Instance of a Class, p. 731 3. Solving the Employee Class Problem, p. 808 14. Chapter 14 1. Operator Overloading, p. 837 2. Class Aggregation, p. 866 3. Solving the NumDays Problem, p. 901 15. Chapter 15 1. Redefining a Base Class Function in a Derived Class, p. 936 2. Polymorphism, p. 947 3. Solving the Employee and ProductionWorker Classes Problem, p. 981 Preface Welcome to the Brief Version of Starting Out with C++: From Control Structures through Objects, 9th edition. This book is intended for use in a two-semester C++ programming sequence, or an accelerated one-semester course. Students new to programming, as well as those with prior course work in other languages, will find this text beneficial. The fundamentals of programming are covered for the novice, while the details, pitfalls, and nuances of the C++ language are explored in depth for both the beginner and more experienced student. The book is written with clear, easy-to-understand language, and it covers all the necessary topics for an introductory programming course. This text is rich in example programs that are concise, practical, and real-world oriented, ensuring that the student not only learns how to implement the features and constructs of C++, but why and when to use them. Changes in the Ninth Edition This book’s pedagogy, organization, and clear writing style remain the same as in the previous edition. Many improvements and updates have been made, which are summarized here: Chapter 2 now includes a discussion of alternative forms of variable initialization, including functional notation, and brace notation (also known as uniform initialization). Chapter 3 now mentions the round function, introduced in C++ 11. Chapter 7 now introduces array initialization much earlier. In Chapter 8, the bubble sort algorithm has been rewritten and improved. A new example of sorting and searching a vector of strings has been added to Chapter 8. In Chapter 9, the section on smart pointers now gives an overview of shared_ptrs and weak_ptrs, in addition to the existing coverage of unique_ptrs. In Chapter 10, a new In the Spotlight section on string tokenizing has been added. Chapter 10 now covers the string-to-number conversion functions that were introduced in C++ 11. The material on unions that previously appeared in Chapter 11 has been moved to Appendix K, available on the book’s companion Website. Chapter 13 has new sections covering: ❍ Member initialization lists. ❍ In-place initialization. ❍ Constructor delegation. Several new topics were added to Chapter 14, including: ❍ Rvalue references and move semantics. ❍ Checking for self-assignment when overloading the = operator. ❍ Using member initialization lists in aggregate classes. Chapter 15 includes a new section on constructor inheritance. Several new programming problems have been added throughout the book. Organization of the Text This text teaches C++ in a step-by-step fashion. Each chapter covers a major set of topics and builds knowledge as the student progresses through the book. Although the chapters can be easily taught in their existing sequence, some flexibility is provided. The diagram shown in Figure P-1 suggests possible sequences of instruction. Figure P-1 Chapter dependency chart Chapter 1 covers fundamental hardware, software, and programming concepts. You may choose to skip this chapter if the class is already familiar with those topics. Chapters 2 through 7 cover basic C++ syntax, data types, expressions, selection structures, repetition structures, functions, and arrays. Each of these chapters builds on the previous chapter and should be covered in the order presented. After Chapter 7 has been covered, you may proceed to Chapters 8, or jump to Chapters 9. After Chapters 9 has been covered, Chapters 10, 11, 12 or 13 may be covered. (If you jump to Chapter 12 at this point, you will need to postpone Sections 12.8, 12.9, and 12.10 until Chapter 11 has been covered.) After Chapter 13, you may cover Chapters 14 and 15 in sequence. This text’s approach starts with a firm foundation in structured, procedural programming before delving fully into object-oriented programming. Brief Overview of Each Chapter Chapter 1: Introduction to Computers and Programming This chapter provides an introduction to the field of computer science and covers the fundamentals of programming, problem solving, and software design. The components of programs, such as key words, variables, operators, and punctuation, are covered. The tools of the trade, such as pseudocode, flow charts, and hierarchy charts, are also presented. Chapter 2: Introduction to C++ This chapter gets the student started in C++ by introducing data types, identifiers, variable declarations, constants, comments, program output, simple arithmetic operations, and C-strings. Programming style conventions are introduced and good programming style is modeled here, as it is throughout the text. Chapter 3: Expressions and Interactivity In this chapter, the student learns to write programs that input and handle numeric, character, and string data. The use of arithmetic operators and the creation of mathematical expressions are covered in greater detail, with emphasis on operator precedence. Debugging is introduced, with a section on hand tracing a program. Sections are also included on simple output formatting, on data type conversion and type casting, and on using library functions that work with numbers. Chapter 4: Making Decisions Here, the student learns about relational operators, relational expressions, and how to control the flow of a program with the if, if/else, and if/else if statements. The conditional operator and the switch statement are also covered. Crucial applications of these constructs are covered, such as menu- driven programs and the validation of input. Chapter 5: Loops and Files This chapter covers repetition control structures. The while loop, do-while loop, and for loop are taught, along with common uses for these devices. Counters, accumulators, running totals, sentinels, and other application- related topics are discussed. Sequential file I/O is also introduced. The student learns to read and write text files, and use loops to process the data in a file. Chapter 6: Functions In this chapter, the student learns how and why to modularize programs, using both void and value returning functions. Argument passing is covered, with emphasis on when arguments should be passed by value versus when they need to be passed by reference. Scope of variables is covered, and sections are provided on local versus global variables and on static local variables. Overloaded functions are also introduced and demonstrated. Chapter 7: Arrays and Vectors In this chapter, the student learns to create and work with single and multi- dimensional arrays. Many examples of array processing are provided including examples illustrating how to find the sum, average, highest, and lowest values in an array, and how to sum the rows, columns, and all elements of a two-dimensional array. Programming techniques using parallel arrays are also demonstrated, and the student is shown how to use a data file as an input source to populate an array. STL vectors are introduced and compared to arrays. Chapter 8: Searching and Sorting Arrays Here, the student learns the basics of sorting arrays and searching for data stored in them. The chapter covers the Bubble Sort, Selection Sort, Linear Search, and Binary Search algorithms. There is also a section on sorting and searching STL vector objects. Chapter 9: Pointers This chapter explains how to use pointers. Pointers are compared to and contrasted with reference variables. Other topics include pointer arithmetic, initialization of pointers, relational comparison of pointers, pointers and arrays, pointers and functions, dynamic memory allocation, and more. Chapter 10: Characters, C-Strings, and More about the string Class This chapter discusses various ways to process text at a detailed level. Library functions for testing and manipulating characters are introduced. C- strings are discussed, and the technique of storing C-strings in char arrays is covered. An extensive discussion of the string class methods is also given. Chapter 11: Structured Data The student is introduced to abstract data types and taught how to create them using structures, unions, and enumerated data types. Discussions and examples include using pointers to structures, passing structures to functions, and returning structures from functions. Chapter 12: Advanced File Operations This chapter covers sequential access, random access, text, and binary files. The various modes for opening files are discussed, as well as the many methods for reading and writing file contents. Advanced output formatting is also covered. Chapter 13: Introduction to Classes The student now shifts focus to the object-oriented paradigm. This chapter covers the fundamental concepts of classes. Member variables and functions are discussed. The student learns about private and public access specifications, and reasons to use each. The topics of constructors, overloaded constructors, and destructors are also presented. The chapter presents a section modeling classes with UML, and how to find the classes in a particular problem. Chapter 14: More about Classes This chapter continues the study of classes. Static members, friends, memberwise assignment, and copy constructors are discussed. The chapter also includes in-depth sections on operator overloading, object conversion, and object aggregation. There is also a section on class collaborations and the use of CRC cards. Chapter 15: Inheritance, Polymorphism, and Virtual Functions The study of classes continues in this chapter with the subjects of inheritance, polymorphism, and virtual member functions. The topics covered include base and derived class constructors and destructors, virtual member functions, base class pointers, static and dynamic binding, multiple inheritance, and class hierarchies. Appendix A: The ASCII Character Set A list of the ASCII and Extended ASCII characters and their codes Appendix B: Operator Precedence and Associativity A chart showing the C++ operators and their precedence Features of the Text Each major section of the text starts with a concept statement. Concept Statements This statement summarizes the ideas of the section. The text has hundreds of complete example programs, each designed to highlight the topic currently being studied. In Example Programs most cases, these are practical, real-world examples. Source code for these programs is provided so that students can run the programs themselves. After each example program, there is a sample of its screen Program Output output. This immediately shows the student how the program should function. Each of these sections provides a programming problem and a detailed, step-by-step analysis In showing the student how to the Spotlight solve it. A series of online videos, developed specifically for this book, is available for viewing at VideoNotes www.pearson.com/gaddis. Icons appear throughout the text alerting the student to videos about specific topics. Checkpoints are questions placed throughout each chapter as a self-test study aid. Answers for all Checkpoint questions can be downloaded from the book’s Checkpoints Website at www.pearson.com/ gaddis. This allows students to check how well they have learned a new topic. Notes appear at appropriate places throughout the text. They are short explanations of Notes interesting or often misunderstood points relevant to the topic at hand. Warnings are notes that caution the student about certain C++ features, programming Warnings techniques, or practices that can lead to malfunctioning programs or lost data. Case studies that simulate real- world applications appear in many chapters throughout the Case Studies text. These case studies are designed to highlight the major topics of the chapter in which they appear. Each chapter presents a thorough and diverse set of review questions, such as fill-in- the-blank and short answer, that check the student’s mastery of the basic material presented in the chapter. These are followed by exercises requiring problem solving and analysis, such as the Review Questions and Exercises Algorithm Workbench, Predict the Output, and Find the Errors sections. Answers to the odd- numbered review questions and review exercises can be downloaded from the book’s Website at www.pearson.com/ gaddis. Each chapter offers a pool of programming exercises designed to solidify the student’s knowledge of the Programming Challenges topics currently being studied. In most cases, the assignments present real-world problems to be solved. When applicable, these exercises include input validation rules. There are several group programming projects throughout the text, intended to be constructed by a team of students. One student might build the program’s user interface, while another student Group Projects writes the mathematical code, and another designs and implements a class the program uses. This process is similar to the way many professional programs are written and encourages team work within the classroom. Available for download from the book’s Website at www.pearson.com/gaddis. This is an ongoing project that instructors can optionally assign to teams of students. It systematically develops a “real- world” software package: a point-of-sale program for the Software Development Project: fictitious Serendipity Serendipity Booksellers Booksellers organization. The Serendipity assignment for each chapter adds more functionality to the software, using constructs and techniques covered in that chapter. When complete, the program will act as a cash register, manage an inventory database, and produce a variety of reports. Throughout the text, new C++11 language features are introduced. Look for the C++11 icon to find these new features. C++11 Supplements Student Online Resources Many student resources are available for this book from the publisher. The following items are available on the Computer Science Portal at www.pearson.com/gaddis: The source code for each example program in the book Access to the book’s VideoNotes A full set of appendices, including answers to the Checkpoint questions and answers to the odd-numbered review questions A collection of valuable Case Studies The complete Serendipity Booksellers Project Online Practice and Assessment with MyLab Programming MyLab Programming helps students fully grasp the logic, semantics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyLab Programming improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages. A self-study and homework tool, a MyLab Programming course consists of hundreds of small practice exercises organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong—and why. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review. MyLab Programming is offered to users of this book in partnership with Turing’s Craft, the makers of the CodeLab interactive programming exercise system. For a full demonstration, to see feedback from instructors and students, or to get started using MyLab Programming in your course, visit www.pearson.com/mylab/programming. Instructor Resources The following supplements are available only to qualified instructors: Answers to all Review Questions in the text Solutions for all Programming Challenges in the text PowerPoint presentation slides for every chapter Computerized test bank Answers to all Student Lab Manual questions Solutions for all Student Lab Manual programs Visit the Pearson Instructor Resource Center (www.pearson.com) for information on how to access instructor resources. Textbook Web site Student and instructor resources, including links to download Microsoft® Visual Studio Express and other popular IDEs, for all the books in the Gaddis Starting Out with series can be accessed at the following URL: www.pearson.com/gaddis Which Gaddis C++ book is right for you? The Starting Out with C++ Series includes three books, one of which is sure to fit your course: Starting Out with C++: From Control Structures through Objects Starting Out with C++: Early Objects Starting Out with C++: Brief Version The following chart will help you determine which book is right for your course. FROM CONTROL STRUCTURES THROUGH OBJECTS EARLY OBJECTS BRIEF VERSION LATE INTRODUCTION OF EARLIER INTRODUCTION OF OBJECTS OBJECTS Classes are introduced in Chapter 7, Classes are introduced in Chapter 13 of after control structures and the standard text and Chapter 11 of the functions, but before arrays and brief text, after control structures, pointers. Their use is then functions, arrays, and pointers. integrated into the remainder of the Advanced OOP topics, such as text. Advanced OOP topics, such as inheritance and polymorphism, are inheritance and polymorphism, are covered in the following two chapters. covered in Chapters 11 and 15. INTRODUCTION OF DATA INTRODUCTION OF DATA STRUCTURES AND RECURSION STRUCTURES AND RECURSION Linked lists, stacks and queues, and binary trees are introduced in the final chapters of the standard text. Recursion Linked lists, stacks and queues, and is covered after stacks and queues, but binary trees are introduced in the before binary trees. These topics are not final chapters of the text, after the covered in the brief text, though it does chapter on recursion. have appendices dealing with linked lists and recursion. Acknowledgments There have been many helping hands in the development and publication of this text. We would like to thank the following faculty reviewers for their helpful suggestions and expertise. Reviewers for the 9th Edition Chia-Chin Chang Lakeland College William Duncan Louisiana State University Pranshu Gupta DeSales University Charles Hardnett Gwinnett Technical College Svetlana Marzelli Atlantic Cape Community College Jie Meichsner St. Cloud State University Ron Del Porto Penn State Erie, The Behrend College Lisa Rudnitsky Baruch College Reviewers for Previous Editions Ahmad Abuhejleh University of Wisconsin–River Falls David Akins El Camino College Steve Allan Utah State University Vicki Allan Utah State University Karen M. Arlien Bismark State College Mary Astone Troy University Ijaz A. Awan Savannah State University Robert Baird Salt Lake Community College Don Biggerstaff Fayetteville Technical Community College Michael Bolton Northeastern Oklahoma State University Bill Brown Pikes Peak Community College Robert Burn Diablo Valley College Charles Cadenhead Richland Community College Randall Campbell Morningside College Wayne Caruolo Red Rocks Community College Cathi Chambley-Miller Aiken Technical College C.C. Chao Jacksonville State University Joseph Chao Bowling Green State University Royce Curtis Western Wisconsin Technical College Joseph DeLibero Arizona State University Michael Dixon Sacramento City College Jeanne Douglas University of Vermont Michael Dowell Augusta State University Qiang Duan Penn State University—Abington William E. Duncan Louisiana State University Daniel Edwards Ohlone College Judy Etchison Southern Methodist University Dennis Fairclough Utah Valley State College Xisheng Fang Ohlone College Mark Fienup University of Northern Iowa Richard Flint North Central College Ann Ford Tyson Florida State University Jeanette Gibbons South Dakota State University James Gifford University of Wisconsin–Stevens Point Leon Gleiberman Touro College Barbara Guillott Louisiana State University Ranette Halverson, Ph.D. Midwestern State University Ken Hang Green River Community College Carol Hannahs University of Kentucky Dennis Heckman Portland Community College Ric Heishman George Mason University Michael Hennessy University of Oregon Ilga Higbee Black Hawk College Patricia Hines Brookdale Community College Mike Holland Northern Virginia Community College Mary Hovik Lehigh Carbon Community College Richard Hull Lenoir-Rhyne College Kay Johnson Community College of Rhode Island Chris Kardaras North Central College Willard Keeling Blue Ridge Community College A.J. Krygeris Houston Community College Sheila Lancaster Gadsden State Community College Ray Larson Inver Hills Community College Michelle Levine Broward College Jennifer Li Ohlone College Norman H. Liebling San Jacinto College Cindy Lindstrom Lakeland College Zhu-qu Lu University of Maine, Presque Isle Heidar Malki University of Houston Debbie Mathews J. Sargeant Reynolds Community College Rick Matzen Northeastern State University Robert McDonald East Stroudsburg University James McGuffee Austin Community College Dean Mellas Cerritos College Lisa Milkowski Milwaukee School of Engineering Marguerite Nedreberg Youngstown State University Lynne O’Hanlon Los Angeles Pierce College Frank Paiano Southwestern Community College Theresa Park Texas State Technical College Mark Parker Shoreline Community College Tino Posillico SUNY Farmingdale Frederick Pratter Eastern Oregon University Susan L. Quick Penn State University Alberto Ramon Diablo Valley College Bazlur Rasheed Sault College of Applied Arts and Technology Farshad Ravanshad Bergen Community College Susan Reeder Seattle University Sandra Roberts Snead College Lopa Roychoudhuri Angelo State University Dolly Samson Weber State University Ruth Sapir SUNY Farmingdale Jason Schatz City College of San Francisco Dr. Sung Shin South Dakota State University Bari Siddique University of Texas at Brownsville William Slater Collin County Community College Shep Smithline University of Minnesota Richard Snyder Lehigh Carbon Community College Donald Southwell Delta College Caroline St. Claire North Central College Kirk Stephens Southwestern Community College Cherie Stevens South Florida Community College Dale Suggs Campbell University Mark Swanson Red Wing Technical College Ann Sudell Thorn Del Mar College Martha Tillman College of San Mateo Ralph Tomlinson Iowa State University David Topham Ohlone College Robert Tureman Paul D. Camp Community College Arisa K. Ude Richland College Peter van der Goes Rose State College Stewart Venit California State University, Los Angeles Judy Walters North Central College John H. Whipple Northampton Community College Aurelia Williams Norfolk State University Chadd Williams Pacific University Vida Winans Illinois Institute of Technology I would also like to thank my family and friends for their support in all of my projects. I am extremely fortunate to have Matt Goldstein as my editor, and Meghan Jacoby as editorial assistant. Their guidance and encouragement made it a pleasure to write chapters and meet deadlines. I am also fortunate to have Demetrius Hall as my marketing manager. His hard work is truly inspiring, and he does a great job of getting this book out to the academic community. The production team, led by Amanda Brands, worked tirelessly to make this book a reality. Thanks to you all! About the Author Tony Gaddis is the principal author of the Starting Out with series of textbooks. He has nearly two decades of experience teaching computer science courses, primarily at Haywood Community College. Tony is a highly acclaimed instructor who was previously selected as the North Carolina Community College Teacher of the Year and has received the Teaching Excellence award from the National Institute for Staff and Organizational Development. The Starting Out with series includes introductory textbooks covering Programming Logic and Design, Alice, C++, Java™, Microsoft® Visual Basic®, Microsoft® Visual C#, Python, and App Inventor, all published by Pearson. Chapter 1 Introduction to Computers and Programming Topics 1. 1.1 Why Program? 2. 1.2 Computer Systems: Hardware and Software 3. 1.3 Programs and Programming Languages 4. 1.4 What Is a Program Made of? 5. 1.5 Input, Processing, and Output 6. 1.6 The Programming Process 7. 1.7 Procedural and Object-Oriented Programming 1.1 Why Program? Concept: Computers can do many different jobs because they are programmable. Think about some of the different ways that people use computers. In school, students use computers for tasks such as writing papers, searching for articles, sending e-mail, and participating in online classes. At work, people use computers to conduct business transactions, communicate with customers and coworkers, analyze data, make presentations, control machines in manufacturing facilities, and many many other tasks. At home, people use computers for tasks such as paying bills, shopping online, social networking, and playing computer games. And don’t forget that smartphones, MP3 players, DVRs, car navigation systems, and many other devices are computers as well. The uses of computers are almost limitless in our everyday lives. Computers can do such a wide variety of things because they can be programmed. This means computers are not designed to do just one job, but any job that their programs tell them to do. A program is a set of instructions that a computer follows to perform a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two commonly used programs. Figure 1-1 A word processing program and a presentation program Programs are commonly referred to as software. Software is essential to a computer because without software, a computer can do nothing. All of the software we use to make our computers useful is created by individuals known as programmers or software developers. A programmer, or software developer, is a person with the training and skills necessary to design, create, and test computer programs. Computer programming is an exciting and rewarding career. Today, you will find programmers working in business, medicine, government, law enforcement, agriculture, academia, entertainment, and almost every other field. Computer programming is both an art and a science. It is an art because every aspect of a program should be carefully designed. Listed below are a few of the things that must be designed for any real-world computer program: The logical flow of the instructions The mathematical procedures The appearance of the screens The way information is presented to the user The program’s “user-friendliness” Documentation, help files, tutorials, and so on There is also a scientific, or engineering, side to programming. Because programs rarely work right the first time they are written, a lot of testing, correction, and redesigning is required. This demands patience and persistence from the programmer. Writing software demands discipline as well. Programmers must learn special languages like C++ because computers do not understand English or other human languages. Languages such as C++ have strict rules that must be carefully followed. Both the artistic and scientific nature of programming make writing computer software like designing a car: Both cars and programs should be functional, efficient, powerful, easy to use, and pleasing to look at. 1.2 Computer Systems: Hardware and Software Concept: All computer systems consist of similar hardware devices and software components. This section provides an overview of standard computer hardware and software organization. Hardware Hardware refers to the physical components of which a computer is made. A computer, as we generally think of it, is not an individual device, but a system of devices. Like the instruments in a symphony orchestra, each device plays its own part. A typical computer system consists of the following major components: The central processing unit (CPU) Main memory Secondary storage devices Input devices Output devices The organization of a computer system is depicted in Figure 1-2. Figure 1-2 Typical devices in a computer system Description The CPU When a computer is performing the tasks that a program tells it to do, we say that the computer is running or executing the program. The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU is the most important component in a computer because without it, the computer could not run software. In the earliest computers, CPUs were huge devices made of electrical and mechanical components such as vacuum tubes and switches. Figure 1-3 shows such a device. The two women in the photo are working with the historic ENIAC computer. The ENIAC, considered by many to be the world’s first programmable electronic computer, was built in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. Figure 1-3 The ENIAC computer U.S. Army Center of Military History Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab technician holding a modern-day microprocessor. In addition to being much smaller than the old electromechanical CPUs in early computers, microprocessors are also much more powerful. Figure 1-4 A microprocessor Creativa/Shutterstock The CPU’s job is to fetch instructions, follow the instructions, and produce some result. Internally, the central processing unit consists of two parts: the control unit and the arithmetic and logic unit (ALU). The control unit coordinates all of the computer’s operations. It is responsible for determining where to get the next instruction and regulating the other major components of the computer with control signals. The arithmetic and logic unit, as its name suggests, is designed to perform mathematical operations. The organization of the CPU is shown in Figure 1-5. Figure 1-5 Organization of a CPU Description A program is a sequence of instructions stored in the computer’s memory. When a computer is running a program, the CPU is engaged in a process known formally as the fetch/decode/execute cycle. The steps in the fetch/decode/execute cycle are as follows: The CPU’s control unit fetches, from main memory, the next Fetch instruction in the sequence of program instructions. The instruction is encoded in the form of a number. The control unit Decode decodes the instruction and generates an electronic signal. The signal is routed to the appropriate component of the computer Execute (such as the ALU, a disk drive, or some other device). The signal causes the component to perform an operation. These steps are repeated as long as there are instructions to perform. Main Memory You can think of main memory as the computer’s work area. This is where the computer stores a program while the program is running, as well as the data with which the program is working. For example, suppose you are using a word processing program to write an essay for one of your classes. While you do this, both the word processing program and the essay are stored in main memory. Main memory is commonly known as random-access memory or RAM. It is called this because the CPU is able to quickly access data stored at any random location in RAM. RAM is usually a volatile type of memory that is used only for temporary storage while a program is running. When the computer is turned off, the contents of RAM are erased. Inside your computer, RAM is stored in small chips. A computer’s memory is divided into tiny storage locations known as bytes. One byte is enough memory to store only a letter of the alphabet or a small number. In order to do anything meaningful, a computer must have lots of bytes. Most computers today have millions, or even billions, of bytes of memory. Each byte is divided into eight smaller storage locations known as bits. The term bit stands for binary digit. Computer scientists usually think of bits as tiny switches that can be either on or off. Bits aren’t actual “switches,” however, at least not in the conventional sense. In most computer systems, bits are tiny electrical components that can hold either a positive or a negative charge. Computer scientists think of a positive charge as a switch in the on position, and a negative charge as a switch in the off position. Each byte is assigned a unique number known as an address. The addresses are ordered from lowest to highest. A byte is identified by its address in much the same way a post office box is identified by an address. Figure 1-6 shows a group of memory cells with their addresses. In the illustration, sample data is stored in memory. The number 149 is stored in the cell with the address 16, and the number 72 is stored at address 23. Figure 1-6 Memory Secondary Storage Secondary storage is a type of memory that can hold data for long periods of time, even when there is no power to the computer. Programs are normally stored in secondary memory and loaded into main memory as needed. Important data such as word processing documents, payroll data, and inventory records is saved to secondary storage as well. The most common type of secondary storage device is the disk drive. A traditional disk drive stores data by magnetically encoding it onto a circular disk. Solid-state drives, which store data in solid-state memory, are increasingly becoming popular. A solid-state drive has no moving parts and operates faster than a traditional disk drive. Most computers have some sort of secondary storage device, either a traditional disk drive or a solid-state drive, mounted inside their case. External storage devices can be used to create backup copies of important data or to move data to another computer. For example, USB (Universal Serial Bus) drives and SD (Secure Digital) memory cards are small devices that appear in the system as disk drives. They are inexpensive, reliable, and small enough to be carried in your pocket. Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are also used for data storage. Data is not recorded magnetically on an optical disc, but is encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect the pits and thus read the encoded data. Optical discs hold large amounts of data, and because recordable CD and DVD drives are now commonplace, they are good mediums for creating backup copies of data. Input Devices Input is any data the computer collects from the outside world. The device that collects the information and sends it to the computer is called an input device. Common input devices are the keyboard, mouse, touchscreen, scanner, digital camera, and microphone. Disk drives, CD/DVD drives, and USB drives can also be considered input devices because programs and information are retrieved from them and loaded into the computer’s memory. Output Devices Output is any information the computer sends to the outside world. It might be a sales report, a list of names, or a graphic image. The information is sent to an output device, which formats and presents it. Common output devices are screens, printers, and speakers. Storage devices can also be considered output devices because the CPU sends them data to be saved. Software If a computer is to function, software is not optional. Everything a computer does, from the time you turn the power switch on until you shut the system down, is under the control of software. There are two general categories of software: system software and application software. Most computer programs clearly fit into one of these two categories. Let’s take a closer look at each. System Software The programs that control and manage the basic operations of a computer are generally referred to as system software. System software typically includes the following types of programs: Operating Systems An operating system is the most fundamental set of programs on a computer. The operating system controls the internal operations of the computer’s hardware, manages all the devices connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other programs to run on the computer. Utility Programs A utility program performs a specialized task that enhances the computer’s operation or safeguards data. Examples of utility programs are virus scanners, file-compression programs, and data-backup programs. Software Development Tools The software tools that programmers use to create, modify, and test software are referred to as software development tools. Compilers and integrated development environments, which we will discuss later in this chapter, are examples of programs that fall into this category. Application Software Programs that make a computer useful for everyday tasks are known as application software. These are the programs that people normally spend most of their time running on their computers. Figure 1-1, at the beginning of this chapter, shows screens from two commonly used applications— Microsoft Word, a word processing program, and Microsoft PowerPoint, a presentation program. Some other examples of application software are spreadsheet programs, e-mail programs, web browsers, and game programs. Checkpoint 1. 1.1 Why is the computer used by so many different people, in so many different professions? 2. 1.2 List the five major hardware components of a computer system. 3. 1.3 Internally, the CPU consists of what two units? 4. 1.4 Describe the steps in the fetch/decode/execute cycle. 5. 1.5 What is a memory address? What is its purpose? 6. 1.6 Explain why computers have both main memory and secondary storage. 7. 1.7 What are the two general categories of software? 8. 1.8 What fundamental set of programs control the internal operations of the computer’s hardware? 9. 1.9 What do you call a program that performs a specialized task, such as a virus scanner, a file-compression program, or a data-backup program? 10. 1.10 Word processing programs, spreadsheet programs, e-mail programs, web browsers, and game programs belong to what category of software? 1.3 Programs and Programming Languages Concept: A program is a set of instructions a computer follows in order to perform a task. A programming language is a special language used to write computer programs. What Is a Program? Computers are designed to follow instructions. A computer program is a set of instructions that tells the computer how to solve a problem or perform a task. For example, suppose we want the computer to calculate someone’s gross pay. Here is a list of things the computer should do: 1. Display a message on the screen asking “How many hours did you work?” 2. Wait for the user to enter the number of hours worked. Once the user enters a number, store it in memory. 3. Display a message on the screen asking “How much do you get paid per hour?” 4. Wait for the user to enter an hourly pay rate. Once the user enters a number, store it in memory. 5. Multiply the number of hours by the amount paid per hour, and store the result in memory. 6. Display a message on the screen that tells the amount of money earned. The message must include the result of the calculation performed in Step 5. Collectively, these instructions are called an algorithm. An algorithm is a set of well-defined steps for performing a task or solving a problem. Notice these steps are sequentially ordered. Step 1 should be performed before Step 2, and so forth. It is important that these instructions be performed in their proper sequence. Although you and I might easily understand the instructions in the pay- calculating algorithm, it is not ready to be executed on a computer. A computer’s CPU can only process instructions that are written in machine language. If you were to look at a machine language program, you would see a stream of binary numbers (numbers consisting of only 1s and 0s). The binary numbers form machine language instructions, which the CPU interprets as commands. Here is an example of what a machine language instruction might look like: 1011010000000101 As you can imagine, the process of encoding an algorithm in machine language is very tedious and difficult. In addition, each different type of CPU has its own machine language. If you wrote a machine language program for computer A then wanted to run it on computer B, which has a different type of CPU, you would have to rewrite the program in computer B’s machine language. Programming languages, which use words instead of numbers, were invented to ease the task of programming. A program can be written in a programming language, such as C++, which is much easier to understand than machine language. Programmers save their programs in text files, then use special software to convert their programs to machine language. Program 1-1 shows how the pay-calculating algorithm might be written in C++. Program 1-1 1 // This program calculates the user's pay. 2 #include 3 using namespace std; 4 5 int main() 6 { 7 double hours, rate, pay; 8 9 // Get the number of hours worked. 10 cout > hours; 12 13 // Get the hourly pay rate. 14 cout > rate; 16 17 // Calculate the pay. 18 pay = hours * rate; 19 20 // Display the pay. 21 cout width; In the example output, the user entered 10 and 20, so 10 is stored in length and 20 is stored in width. Notice the user separates the numbers by spaces as they are entered. This is how cin knows where each number begins and ends. It doesn’t matter how many spaces are entered between the individual numbers. For example, the user could have entered 10 20 Note: The Enter key is pressed after the last number is entered. cin will also read multiple values of different data types. This is shown in Program 3-3. Program 3-3 1 // This program demonstrates how cin can read multiple values 2 // of different data types. 3 #include 4 using namespace std; 5 6 int main() 7 { 8 int whole; 9 double fractional; 10 char letter; 11 12 cout > whole >> fractional >> letter; 14 cout sold; 34 store2 −= sold; // Adjust store 2's inventory. 35 36 // Get the number of widgets sold at store 3. 37 cout > sold; 39 store3 −= sold; // Adjust store 3's inventory. 40 41 // Display each store's current inventory. 42 cout power; bigNum = num; while (count++ < power); bigNum *= num; cout > choice; 35 36 // Validate the menu selection. 37 while (choice < ADULT_CHOICE || choice > QUIT_CHOICE) 38 { 39 cout > choice; 41 } 42 43 // If the user does not want to quit, proceed. 44 if (choice != QUIT_CHOICE) 45 { 46 // Get the number of months. 47 cout > months; 49 50 // Display the membership fees. 51 switch (choice) 52 { 53 case ADULT_CHOICE: 54 showFees(ADULT, months); 55 break; 56 case CHILD_CHOICE: 57 showFees(CHILD, months); 58 break; 59 case SENIOR_CHOICE: 60 showFees(SENIOR, months); 61 } 62 } 63 } while (choice != QUIT_CHOICE); 64 return 0; 65 } 66 67 //***************************************************************** 68 // Definition of function showMenu which displays the menu. * 69 //***************************************************************** 70 71 void showMenu() 72 { 73 cout