ebook img

C++ for Everyone PDF

696 Pages·2010·13.934 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview C++ for Everyone

C + + F O R E V E R Y O N E This page intentionally left blank C + + F O R E V E R Y O N E SECOND EDITION Cay Horstmann San Jose State University John Wiley & Sons, Inc. VICE PRESIDENT AND EXECUTIVE PUBLISHER Don Fowley EXECUTIVE EDITOR Beth Lang Golub EDITORIAL PROGRAM ASSISTANT Michael Berlin PRODUCTION SERVICES MANAGER Dorothy Sinclair SENIOR PRODUCTION EDITOR Janet Foxman EXECUTIVE MARKETING MANAGER Christopher Ruel MARKETING ASSISTANT Diana Smith CREATIVE DIRECTOR Harry Nolan SENIOR PHOTO EDITOR Lisa Gee SENIOR DESIGNER Madelyn Lesure EXECUTIVE MEDIA EDITOR Tom Kulesa PRODUCTION SERVICES Cindy Johnson COVER PHOTO © Ricardo Azoury/iStockphoto 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. (cid:39) Founded in 1807, John Wiley & 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 (cid:185) 2012, 2009 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be re- produced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, pho- tocopying, 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, Dan- vers, MA 01923, website www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748- 6011, 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 instruc- tions 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., 1959- C++ 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 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 PREFACE This book is an introduction to C++ and computer programming that focuses on the essentials—and 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 program- ming 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. 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 instruc- tions. 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. 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. This book uses the C++ programming language as a vehicle for introducing com- puter sci ence 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. Photographs present visual analogies that explain the nature and behavior of computer concepts. Step-by- step 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 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 prac- tices 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 vi Preface New to This Edition Problem Solving Strategies This edition adds practical, step-by-step illustrations of techniques that can help stu- dents 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) • Stepwise Refinement • First Do It By Hand (doing sample • Adapting Algorithms calculations by hand) • Discover Algorithms by Manipulat- • Flowcharts ing Physical Objects • Test Cases • Draw a Picture (pointer diagrams) • Hand-Tracing • Tracing Objects (identifying state and • Storyboards behavior) • Reusable Functions • Discovering Classes Optional Engineering Exercises End-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. Addi- tional exercises are available on the book’s companion web site. New and Reorganized Topics All 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. Debug- ging is now introduced in a lengthy Worked Example in Chapter 5. Arrays are cov- ered before vectors are introduced in Chapter 6, and a new section on vector algo- rithms 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. A Tour of the Book The 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 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. Preface vii File processing is the subject of Chapter 8. Section 8.1 can be covered sooner for an intro duction to reading and writing text files. The remainder of the chapter gives addi tional 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 individu- ally 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 Figure 1 shows the dependencies between the chapters. Fundamentals 1. Introduction Online 2. Fundamental Data Types 3. Decisions 4. Loops A gentle introduction to recursion is optional 5. Functions Section 8.1 contains the core material 6. Arrays and Vectors 12. Sorting and 7. Pointers 8. Streams 9. Classes 11. Recursion Searching Sections 13. Lists, Stacks, 10. Inheritance 7.1 and 7.4 are and Queues required 14. Sets, Maps, Figure 1 Priority Queues Chapter Dependencies viii Walkthrough A Walkthrough of the Learning Aids The 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 fea- tures, such as chapter objectives and a wealth of exercises, each chapter contains ele- ments geared to today’s visual learner. 4.3 The for Loop 143 4.4 The for Loop Throughout each chapter, margin notes show where Tusheed f worh leono pa is Ititm oeftse. nY hoaup pcaenn su tshea ta ywohiul we laonot pto t hexaet cius tceo an sterqoulleendc be yo fa s ctaotuenmteenr,t sa sa igniv tehne nfuomllobweri nogf new concepts are introduced value runs from a example: starting point to an and provide an outline of key ideas. econndsintagn pt oininctr ewmitehn at cwohuinltee r( c=o u1n;t e/r/ <I=n 1it0i)al i/z/e tChhe eccoku tnhtee rcounter or decrement. { cout << counter << endl; counter++; // Update the counter } Because this loop type is so common, there is a special form for it, called the for loop (see Syntax 4.2). for (counter = 1; counter <= 10; counter++) { cout << counter << endl; } Some people call this loop count-controlled. In contrast, the while loop of the preceding section can be called an event-controlled loop because it executes until an event occurs (for example, when the balance reaches the target). Another commonly-used term for a count-controlled loop is definite. You know from the outset that the loop body will be executed a definite number of times––ten times in our example. In contrast, you do not know how many iterations it takes to accumulate a target balance. Such a loop is called indefinite. Annotated syntax boxes The for loop neatly groups the initialization, condi- provide a quick, visual overview timiopno, ratnandt utop draetael izeex pthreasts itohnesse teoxgpertehsesri.o nHso awree vneor,t eitx ei-s Yfoour cloaonp v aissu aanli zoer dtehrel y of new language constructs. cuted together (see Figure 3). sequence of steps. Syntax 4.2 for Statement These three expressions should be related. See page 147. Annotations explain This initialization The loop is This update is required components hbeafpopreen st hoen cloeo p starts. ethxeisc uctoendd iwtiohnil ei s true. eexaecchu titeedr aatfitoenr. and point to more information for (int i = 5; i <= 10; i++) on common errors or best practices { associated with the syntax. definedT hoSene levy a piranig atebh l1ies 4 if4 oi.sr loop. } sum = sum + i; Thi s l o o p eSxeeec uptaesg e6 1 t4im7.es. Analogies to everyday objects are used to explain the nature and behavior of concepts such as variables, data Like a variable in a computer types, loops, and more. program, a parking space has an identifier and a contents.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.