C++ for Everybody

Download C++ for Everybody

Post on 08-Nov-2014

124 views

Category:

Documents

0 download

Embed Size (px)

DESCRIPTION

C++ for everbody, teachs you C plus plus

TRANSCRIPT

<p>This page intentionally left blank</p> <p>C++ for EvEryonE</p> <p>This page intentionally left blank</p> <p>C++ for EvEryonE</p> <p>Second edition</p> <p>cay HorstmannSan Jose State University</p> <p>John Wiley &amp; Sons, Inc.</p> <p>VICE PRESIDENT AND EXECUTIVE PUBLISHER EXECUTIVE EDITOR EDITORIAL PROGRAM ASSISTANT PRODUCTION SERVICES MANAGER SENIOR PRODUCTION EDITOR EXECUTIVE MARKETING MANAGER MARKETING ASSISTANT CREATIVE DIRECTOR SENIOR PHOTO EDITOR SENIOR DESIGNER EXECUTIVE MEDIA EDITOR PRODUCTION SERVICES COVER PHOTO</p> <p>Don Fowley Beth Lang Golub Michael Berlin Dorothy Sinclair Janet Foxman Christopher Ruel Diana Smith Harry Nolan Lisa Gee Madelyn Lesure Tom Kulesa Cindy Johnson Ricardo Azoury/iStockphoto</p> <p>This book was set in Stempel Garamond by Publishing Services, and printed and bound by RRD Jefferson City. The cover was printed by RRD Jefferson City. This book is printed on acid-free paper. Founded in 1807, John Wiley &amp; Sons, Inc. has been a valued source of knowledge and understanding for more than 200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is built on a foundation of principles that include responsibility to the communities we serve and where we live and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental, social, economic, and ethical challenges we face in our business. Among the issues we are addressing are carbon impact, paper specifications and procurement, ethical conduct within our business and among our vendors, and community and charitable support. For more information, please visit our website: www.wiley.com/go/ citizenship. Copyright 2012, 2009 John Wiley &amp; Sons, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, website www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley &amp; Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 7486011, fax (201) 748-6008, website www.wiley.com/go/permissions. Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instructions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. Outside of the United States, please contact your local representative. Library of Congress Cataloging in Publication Data: Horstmann, Cay S., 1959C++ for everyone / Cay S. Horstmann. -- 2nd ed. p. cm. Includes index. ISBN 978-0-470-92713-7 (pbk.) 1. C++ (Computer program language) I. Title. QA76.73.C153H6685 2010 005.13'3--dc22 2010039907</p> <p>ISBN 978-0-470-92713-7 (Main Book) ISBN 978-0-470-92092-3 (Binder-Ready Version) Printed in the United States of America 10 9 8 7 6 5 4 3 2 1</p> <p>P r E fa C EThis book is an introduction to C++ and computer programming that focuses on the essentialsand on effective learning. The book is designed to serve a wide range of student interests and abilities and is suitable for a first course in programming for computer scientists, engineers, and students in other disciplines. No prior programming experience is required, and only a modest amount of high school algebra is needed. Here are the key features of this book:Guidance and worked examples help students succeed.</p> <p>Beginning programmers often ask How do I start? Now what do I do? Of course, an activity as complex as programming cannot be reduced to cookbook-style instructions. However, step-by-step guidance is immensely helpful for building confidence and providing an outline for the task at hand. Problem Solving sections stress the importance of design and planning. How To guides help students with common programming tasks. Additional Worked Examples are available online.Practice makes perfect.</p> <p>Of course, programming students need to be able to implement nontrivial programs, but they first need to have the confidence that they can succeed. This book contains a substantial number of self-check questions at the end of each section. Practice It pointers suggest exercises to try after each section. At the end of each chapter, you will find a great variety of programming assignments, ranging from simple practice problems to realistic applications.teach computer science principles, not just c++ or object-orientation.</p> <p>This book uses the C++ programming language as a vehicle for introducing computer science concepts. A substantial subset of the C++ language is covered, focusing on the modern features of standard C++ that make students productive. The book takes a traditional route, stressing control structures, procedural decomposition, and array algorithms, before turning to the design of classes in the final chapters.A visual approach motivates the reader and eases navigation.</p> <p>Photographs present visual analogies that explain the nature and behavior of computer concepts. Step-bystep figures illustrate complex program operations. Syntax boxes and example tables present a variety of typical and special cases in a compact format. It is easy to get the lay of the land by browsing the visuals, before focusing on the textual material.Focus on the essentials while being technically accurate.Visual features help the reader</p> <p>An encyclopedic coverage is not helpful for a begin- with navigation. ning programmer, but neither is the opposite reducing the material to a list of simplistic bullet points. In this book, the essentials are presented in digestible chunks, with separate notes that go deeper into good practices or language features when the reader is ready for the additional information. You will not find artificial over-simplifications that give an illusion of knowledge.v</p> <p>vi</p> <p>Preface</p> <p>new to This EditionProblem Solving StrategiesThis edition adds practical, step-by-step illustrations of techniques that can help students devise and evaluate solutions to programming problems. Introduced where they are most relevant, these strategies address barriers to success for many students. Strategies included are: Algorithm Design (with pseudocode) First Do It By Hand (doing sample calculations by hand) Flowcharts Test Cases Hand-Tracing Storyboards Reusable Functions Stepwise Refinement Adapting Algorithms Discover Algorithms by Manipulating Physical Objects Draw a Picture (pointer diagrams) Tracing Objects (identifying state and behavior) Discovering Classes</p> <p>optional Engineering ExercisesEnd-of-chapter exercises have been enhanced with problems from scientific and engineering domains. Geared to students learning C++ for a technical major, the exercises are designed to illustrate the value of programming in those fields. Additional exercises are available on the books companion web site.</p> <p>new and reorganized TopicsAll chapters were revised and enhanced to respond to user feedback and improve the flow of topics. Loop algorithms are now introduced explicitly in Chapter 4. Debugging is now introduced in a lengthy Worked Example in Chapter 5. Arrays are covered before vectors are introduced in Chapter 6, and a new section on vector algorithms builds on the array algorithms presented earlier in the chapter. A new optional section on structure types is now in Chapter 7. New example tables, photos, and exercises appear throughout the book.</p> <p>a Tour of the BookThe core material of the book is:Chapter 1. Introduction Chapter 2. Fundamental Data Types Chapter 3. Decisions Chapter 4. Loops Chapter 5. Functions Chapter 6. Arrays and Vectors</p> <p>In a course for engineers with a need for systems and embedded programming, you will want to cover Chapter 7 on pointers. Sections 7.1 and 7.4 are sufficient for using pointers with polymorphism in Chapter 10.</p> <p>Preface</p> <p>vii</p> <p>File processing is the subject of Chapter 8. Section 8.1 can be covered sooner for an introduction to reading and writing text files. The remainder of the chapter gives additional material for practical applications. Chapters 9 and 10 introduce the object-oriented features of C++. Chapter 9 introduces class design and implementation. Chapter 10 covers inheritance and polymorphism. Four additional chapters are available on the Web. They can be used individually for a capstone chapter, or they can be combined for teaching a two-semester course. (They can also be incorporated into a custom print version of the text; ask your Wiley sales representative for details.)Chapter 11. Recursion Chapter 12. Sorting and Searching Chapter 13. Lists, Stacks, and Queues Chapter 14. Sets, Maps, and Priority Queues</p> <p>Figure 1 shows the dependencies between the chapters.</p> <p>Fundamentals Online</p> <p>1. Introduction</p> <p>2. Fundamental Data Types</p> <p>3. Decisions</p> <p>4. Loops</p> <p>5. Functions</p> <p>A gentle introduction to recursion is optional</p> <p>Section 8.1 contains the core material</p> <p>6. Arrays and Vectors</p> <p>7. Pointers</p> <p>8. Streams</p> <p>9. Classes</p> <p>11. Recursion</p> <p>12. Sorting and Searching</p> <p>Sections 7.1 and 7.4 are required Figure 1</p> <p>13. Lists, Stacks, and Queues</p> <p>10. Inheritance</p> <p>Chapter Dependencies</p> <p>14. Sets, Maps, Priority Queues</p> <p>viii</p> <p>Walkthrough</p> <p>a Walkthrough of the Learning aidsThe pedagogical elements in this book work together to focus on and reinforce key concepts and fundamental principles of programming, with additional tips and detail organized to support and deepen these fundamentals. In addition to traditional features, such as chapter objectives and a wealth of exercises, each chapter contains elements geared to todays visual learner.</p> <p>4.3 The for Loop</p> <p>143</p> <p>Throughout each chapter, margin notes show where new concepts are introduced and provide an outline of key ideas.</p> <p>4.4 The for LoopThe for loop is used when a value runs from a starting point to an ending point with a constant increment or decrement.</p> <p>It often happens that you want to execute a sequence of statements a given number of times. You can use a while loop that is controlled by a counter, as in the following example:counter = 1; // Initialize the counter while (counter (greater than), relational operator, 83t, 105t &gt;= (greater than or equal), relational operator, 83t, 105t - (hyphen), in option names, 365 &lt; (less than), relational operator, 83t, 105t ), 337, 422423 artificial intelligence, 112113 ASCII codes, 494t assignment = (equal sign), assignment operator, 3435 combining with arithmetic, 47 asterisk (*) indirection operator, 309 multiplication operator, 40, 105t asymmetric loop bounds vs. symmetric, 147 at function, 498 atoi function, 322 Augusta, Ada, 290 autonomous vehicles, 113 averaging array elements, 257 values, with loops, 157158 blank spaces, coding guidelines, 486 BMP images, reading/writing, 373376 bool, reserved word, 489t bool data type, 103104. boolalpha manipulator, 444446, 496 Boole, George, 103 Boolean operations operator, summary of, 104 operator precedence, 105t truth tables, 104 variables, 103104 Boolean operations, &amp;&amp; (AND) confusing with || (OR), 107 description, 105t inverting, 108 short-circuit evaluation, 108 Boolean operations, ! (NOT) description, 105t inverting conditions, 108 Boolean operations, || (OR) confusing with &amp;&amp; (AND), 107 description, 105t inverting, 108 short-circuit evaluation, 108 Boolean variables, 103104 to control a loop, 152 bottle volume program, 3051 boundary conditions, testing, 102 bounds errors, arrays, 252253, 254255 braces ({ }) coding guidelines, 487 in if statements, 7980, 98 break, reserved word, 489t break statements coding guidelines, 486 loop termination, 153 missing, 93 breaking complex tasks into simple steps recursive thinking, 229230 stepwise refinement, 210215 breaking out of loops, 153 breaking statements, coding guidelines, 486 buffer overrun attacks, 255 bugs, historical first, 138</p> <p>B</p> <p>Babbage, Charles, 290 baby-name program, 354357 babynames.cpp (ch08), 356357 backing up data, 1011 backslash (\) displaying as a literal, 14 escape sequence, 14, 493t backslash, double quote (\"), double quote escape sequence, 493t backslash, question mark (\?), question mark escape sequence, 493t backslash, quote (\'), single quote escape sequence, 493t bank account withdrawal simulation, 220225 base classes constructing, 451 constructor syntax, 451 definition, 442 forgetting the name of, 455 inheriting derived classes from, 451455 overriding with derived classes, 448 bell-curve distribution, simulating, 329332 binary files, reading/writing, 372373 binary search, 264265 black box, functions as, 195 blank lines, coding guidelines, 486</p> <p>\b (backspace escape sequence), 493t</p> <p>C</p> <p>C++ programs case sensitivity, 8 ending statements, 1314 history of, 6 inventor of, 6 main function, 12 namespaces, 12 naming conflicts, avoiding, 12</p> <p>Index 511style guide. See coding guidelines syntax, 12 C strings \0, null terminator, 321 atoi function, 322 converting characters to integers, 322 converting to/from C++, 322 definition, 320321 functions for, 323324 length, determining, 321 manipulating directly, 323324 strlen function, 321 terminating, 321 caesar.cpp (ch08), 366367 calling constructors, 405 functions, 194, 226230 member functions from member functions, 399402 member functions from pointers, 422423 can volume program, 3051 carriage return escape sequence (\r), 493t case converting, 322323, 496 determining, 496 case, reserved word, 93, 489t case sensitivity C++ programs, 8 coding guidelines, 486 definition, 16 file systems, 9 if statement comparisons, 86 integrated development environment, 8 misspelling words, 16 variables, 33 cash register simulation, 400402, 418421 cashregister.cpp (ch09), 419 cashregister.h (ch09), 418 casts, 46 The Cathedral and the Bazaar, 426 code library, summary, 495496 chads, 412 char, reserved word, 489t char* pointer, 322 char type, 320 character arrays, strings, 321322 character codes ASCII codes, 494t escape sequences, 493t characters. See also strings converting to integers, 322 definition, 56 extracting from strings, 5860, 496 reading from text files, 358359 check-printing program, 211215 chips, definition, 3 cin (&gt;&gt;) assigning values to variables, 48 reading input from a screen, 48 class, reserved word, 392394, 489t classes. See also public interface aggregation relationships, 414415 coding guidelines, 485 definition, 390 discovering, 414417 has-a relationships, 414415, 442 is-a relationships, 442 naming conventions, 392 classes, defining constru...</p>