Top Banner
562
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

This page intentionally left blank C++ for EvEryonEcfe2_fm_pi_xxvi.indd 1 10/28/10 5:08 PMThis page intentionally left blank C++ for EvEryonES e conde di ti oncay Horstmann San Jose State UniversityJohn Wiley & Sons, Inc.cfe2_fm_pi_xxvi.indd 3 10/28/10 5:08 PMVICE PRESIDENT AND EXECUTIVE PUBLISHERDon FowleyEXECUTIVE EDITORBeth Lang GolubEDITORIAL PROGRAM ASSISTANTMichael BerlinPRODUCTION SERVICES MANAGERDorothy SinclairSENIOR PRODUCTION EDITORJanet Foxman EXECUTIVE MARKETING MANAGERChristopher RuelMARKETING ASSISTANTDiana SmithCREATIVE DIRECTORHarry NolanSENIOR PHOTO EDITORLisa Gee SENIOR DESIGNERMadelyn Lesure EXECUTIVE MEDIA EDITORTom KulesaPRODUCTION SERVICES Cindy JohnsonCOVER PHOTO Ricardo Azoury/iStockphotoThis 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 & 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 fulfll 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,paperspecifcationsandprocurement,ethicalconductwithinourbusinessandamongourvendors, and community and charitable support. For more information, please visit our website: www.wiley.com/go/citizenship.Copyright 2012, 2009John 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 qualifed 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 2010005.13'3--dc222010039907ISBN978-0-470-92713-7(Main Book)ISBN978-0-470-92092-3(Binder-Ready Version)Printed in the United States of America10987654321cfe2_fm_pi_xxvi.indd 4 10/28/10 5:08 PMPrEfaCEvThis 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 frst course in programming for computer scientists, engineers, and students in other disciplines. No prior program-mingexperienceisrequired,andonlyamodestamountofhighschoolalgebrais 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 confdence 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 frst need to have the confdence 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 fnd a great variety of programming assignments, ranging from simple practice problems to realistic applications.teach computer science principles, not just c++ or object-orientation.ThisbookusestheC++programminglanguageasavehicleforintroducingcom-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 fnal 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 fgures illustrate complex program operations. Syntaxboxesandexampletablespresentavariety 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. An encyclopedic coverage is not helpful for a begin-ningprogrammer,butneitheristheoppositereducing 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 languagefeatureswhenthereaderisreadyfortheadditionalinformation. You will not fnd artifcial over-simplifcations that give an illusion of knowledge. Visual features help the readerwith navigation.cfe2_fm_pi_xxvi.indd 5 10/28/10 5:08 PMviPreface new to This EditionProblem Solving StrategiesThis edition adds practical, step-by-step illustrations of techniques that can help stu-dentsdeviseandevaluatesolutionstoprogrammingproblems.Introducedwhere 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)FlowchartsTest CasesHand-TracingStoryboardsReusable FunctionsStepwise RefnementAdapting Algorithms Discover Algorithms by Manipulat-ing Physical ObjectsDraw a Picture (pointer diagrams)Tracing Objects (identifying state and behavior)Discovering Classesoptional Engineering ExercisesEnd-of-chapterexerciseshavebeenenhancedwithproblemsfromscientifcand engineeringdomains.GearedtostudentslearningC++foratechnicalmajor,the exercises are designed to illustrate the value of programming in those felds. Addi-tional exercises are available on the books companion web site.new and reorganized TopicsAll chapters were revised and enhanced to respond to user feedback and improve the fow 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 sectiononstructuretypesisnowinChapter7.Newexampletables,photos,and exercises appear throughout the book.a Tour of the BookThe core material of the book is:Chapter 1.IntroductionChapter 2.Fundamental Data TypesChapter 3.DecisionsChapter 4.LoopsChapter 5.FunctionsChapter 6.Arrays and VectorsIn 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 suffcient for using pointers with polymorphism in Chapter 10.cfe2_fm_pi_xxvi.indd 6 10/28/10 5:08 PMPrefaceviiFile processing is the subject of Chapter 8. Section 8.1 can be covered sooner for an intro duction to reading and writing text fles. The remainder of the chapter gives addi tional material for practical applications.Chapters9and10introducetheobject-orientedfeaturesofC++.Chapter9 introducesclassdesignandimplementation.Chapter10coversinheritanceand polymorphism. Four additional chapters are available on the Web. They can be used individu-allyforacapstonechapter,ortheycanbecombinedforteachingatwo-semester course. (They can also be incorporated into a custom print version of the text; ask your Wiley sales representative for details.)Chapter 11.RecursionChapter 12.Sorting and SearchingChapter 13.Lists, Stacks, and QueuesChapter 14.Sets, Maps, and Priority QueuesFigure 1 shows the dependencies between the chapters. Figure 1 Chapter DependenciesSection 8.1 contains the core materialSections 7.1 and 7.4 are requiredA gentle introduction to recursion is optional1. Introduction2. Fundamental Data Types3. Decisions4. Loops5. Functions6. Arrays and Vectors9. Classes 11. Recursion12. Sorting and Searching8. Streams13. Lists, Stacks, and Queues14. Sets, Maps,Priority Queues7. Pointers10. InheritanceFundamentalsOnlinecfe2_fm_pi_xxvi.indd 7 10/28/10 5:08 PMviiiWalkthrough 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 fea-tures, such as chapter objectives and a wealth of exercises, each chapter contains ele-ments geared to todays visual learner.4.3The for Loop 1434.4The for LoopIt 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 counterwhile (counter name;(User input: Harry Morgan)name contains "Harry" The >> operator places the next word into the string variable.cout > name >> last_name;(User input: Harry Morgan)name contains "Harry", last_name contains "Morgan"Use multiple >> operators to read more than one word.string greeting = "H & S";int n = greeting.length();n is set to 5 Each space counts as one character.string str = "Sally";string str2 = str.substr(1, 3);str2 is set to "all" Extracts the substring of length 3 starting at position 1. (The initial position is 0.)string str = "Sally";string str2 = str.substr(1);str2 is set to "ally" If you omit the length, all characters from the position until the end are included.string a = str.substr(0, 1); a is set to the initial letter in strExtracts the substring of length 1 starting at position 0.string b = str.substr(str.length() - 1); b is set to the last letter in strThe last letter has position str.length() - 1. We need not specify the length.What is the length of the string "C++ Program"?26. Consider this string variable.string str = "C++ Program";Give a call to the substr member function that returns the substring "gram".27. Use string concatenation to turn the string variable str from Self Check 26 to "C++ Programming".28. What does the following statement sequence print?string str = "Harry";cout > operator to read a value and place it in a variable.You use manipulators to specify how val ues should be formatted.carryouthandcalculationswhendevelopinganalgorithm.Pick concrete values for a typical situation to use in a hand calculation.Writeprogramsthatprocessstrings.Strings are sequences of characters.Use the + operator to concatenate strings; that is, put them together to yield a longer string.The length member function yields the number of characters in a string.Chap t e r s ummaryA member function is invoked using the dot notation.Use the substr member function to extract a substring of a stringr2.1 What is the value of mystery after this sequence of statements?int mystery = 1;mystery = 1 - 2 * mystery;mystery = mystery + 1;r2.2 What is wrong with the following sequence of statements?int mystery = 1;mystery = mystery + 1;int mystery = 1 - 2 * mystery;r2.3 Write the following mathematical expressions in C++.r2.4 Write the following C++ expressions in mathematical notation.a.dm = m * (sqrt(1 + v / c) / sqrt(1 - v / c) - 1);b.volume = PI * r * r * h;c.volume = 4 * PI * pow(r, 3) / 3;d.z = sqrt(x * x + y * y);r2.5 What are the values of the following expressions? In each line, assume thatdouble x = 2.5;double y = -1.5;int m = 18;int n = 4;a.x + n * y - (x + n) * yb.m / n + m % nc.5 * x - n / 5d.1 - (1 - (1 - (1 - (1 - n))))e.sqrt(sqrt(n))r2.6 What are the values of the following expressions? In each line, assume thatstring s = "Hello";string t = "World";r e V I e We x e r CI s e scfe2_ch02_p29_74.indd 62 10/27/10 2:30 PMreview exercises63A member function is invoked using the dot notation.Use the substr member function to extract a substring of a stringr2.1 What is the value of mystery after this sequence of statements?int mystery = 1;mystery = 1 - 2 * mystery;mystery = mystery + 1;r2.2 What is wrong with the following sequence of statements?int mystery = 1;mystery = mystery + 1;int mystery = 1 - 2 * mystery;r2.3 Write the following mathematical expressions in C++.s s v t gtGap m m= + +=+= +0 022321 21241( )FV PVINT1000YRS= + c a b ab2 22 cosr2.4 Write the following C++ expressions in mathematical notation.a.dm = m * (sqrt(1 + v / c) / sqrt(1 - v / c) - 1);b.volume = PI * r * r * h;c.volume = 4 * PI * pow(r, 3) / 3;d.z = sqrt(x * x + y * y);r2.5 What are the values of the following expressions? In each line, assume thatdouble x = 2.5;double y = -1.5;int m = 18;int n = 4;a.x + n * y - (x + n) * yb.m / n + m % nc.5 * x - n / 5d.1 - (1 - (1 - (1 - (1 - n))))e.sqrt(sqrt(n))r2.6 What are the values of the following expressions? In each line, assume thatstring s = "Hello";string t = "World";r e V I e We x e r CI s e scfe2_ch02_p29_74.indd 63 10/27/10 2:30 PM64Chapter 2 Fundamental data types a.s.length() + t.length()b.s.substr(1, 2)c.s.substr(s.length() / 2, 1)d.s + te.t + sr2.7 Find at least fve compile-time errors in the following program.#include iostreamint main();{ cout 10 kg."