University Press of Florida

Programming Fundamentals: A Modular Structured Approach Using C++

Buy This Book ( Related URL )
MISSING IMAGE

Material Information

Title:
Programming Fundamentals: A Modular Structured Approach Using C++
Physical Description:
Book
Language:
en-US
Creator:
Busbee, Kenneth Leroy, Connexions, Rice University

Subjects

Subjects / Keywords:
Program Planning, Program Design, Data, Operators, Data Types, Integrated Development Environment, Program Control Functions, Pseudocode, Structured Programming, Boolean Logic, Multiway Selection, Test Loops, Recursion, Arrays, Compiler Directives, Object Oriented Programming, OGT+ ISBN: 9781616100650
Programming,Programming Languages
Mathematics / Technology

Notes

Abstract:
The approach of this text is to take learners through a progression of materials in order to develop skills of modular, structured programming. The text was written, for the most part, without consideration of a specific programming language. However, in many cases the C++ language is discussed as part of the explanation of the concept. Often the examples used for C++ are exactly the same for the Java programming language.
General Note:
Expositive
General Note:
Community College, Higher Education
General Note:
http://www.ogtp-cart.com/product.aspx?ISBN=9781616100650
General Note:
Adobe PDF Reader
General Note:
Textbook
General Note:
http://florida.theorangegrove.org/og/file/9391cbd0-7459-27f5-f2a9-414a702a912e/1/Programming.pdf

Record Information

Source Institution:
University of Florida
Rights Management:
Copyright © 2008 Kenneth Leroy Busbee. This selection and arrangement of content is licensed under the Creative Commons Attribution License: http://creativecommons.org/licenses/by/2.0/
Resource Identifier:
isbn - 9781616100650
System ID:
AA00011661:00001


This item is only available as the following downloads:


Full Text

PAGE 1

ProgrammingFundamentals-AModular StructuredApproachusingC++ By: KennethLeroyBusbee

PAGE 3

ProgrammingFundamentals-AModular StructuredApproachusingC++ By: KennethLeroyBusbee Online: < http://cnx.org/content/col10621/1.17/ > CONNEXIONS RiceUniversity,Houston,Texas

PAGE 4

2008KennethLeroyBusbee ThisselectionandarrangementofcontentislicensedundertheCreativeCommonsAttributionLicense: http://creativecommons.org/licenses/by/2.0/

PAGE 5

TableofContents Preface ...............................................................................................1 AuthorAcknowledgements .........................................................................5 OrientationandSyllabus ...........................................................................7 11.IntroductiontoProgramming 1.1 SystemsDevelopmentLifeCycle............................................................11 1.2 BloodshedDev-C++5Compiler/IDE......................................................13 1.3 ModularizationandC++ProgramLayout.................................................16 1.4 Practice1:IntroductiontoProgramming...................................................20 Solutions........................................................................................23 22.ProgramPlanning&Design 2.1 ProgramDesign............................................................................25 2.2 Pseudocode................................................................................26 2.3 TestData..................................................................................27 2.4 Practice2:ProgramPlanning&Design....................................................29 Solutions........................................................................................32 33.Data&Operators 3.1 DataTypesinC++........................................................................33 3.2 IdentierNames............................................................................35 3.3 ConstantsandVariables....................................................................36 3.4 DataManipulation.........................................................................37 3.5 AssignmentOperator.......................................................................38 3.6 ArithmeticOperators.......................................................................39 3.7 DataTypeConversions.....................................................................40 3.8 Practice3:Data&Operators..............................................................42 Solutions........................................................................................45 44.OftenUsedDataTypes 4.1 IntegerDataType..........................................................................47 4.2 Floating-PointDataType..................................................................48 4.3 StringDataType..........................................................................49 4.4 ArithmeticAssignmentOperators..........................................................50 4.5 LvalueandRvalue..........................................................................51 4.6 IntegerDivisionandModulus..............................................................53 4.7 Practice4:OftenUsedDataTypes.........................................................55 Solutions........................................................................................57 55.IntegratedDevelopmentEnvironment 5.1 IntegratedDevelopmentEnvironment.......................................................59 5.2 StandardInputandOutput................................................................65 5.3 CompilerDirectives........................................................................68 5.4 Practice5:IntegratedDevelopmentEnvironment...........................................69 Solutions........................................................................................72 66.ProgramControlFunctions 6.1 PseudocodeExamplesforFunctions........................................................73 6.2 HierarchyorStructureChart...............................................................74 6.3 ProgramControlFunctions.................................................................75 6.4 VoidDataType............................................................................77

PAGE 6

iv 6.5 DocumentationandMakingSourceCodeReadable.........................................78 6.6 Practice6:ProgramControlFunctions.....................................................82 Solutions........................................................................................87 77.SpecicTaskFunctions 7.1 SpecicTaskFunctions.....................................................................89 7.2 GlobalvsLocalDataStorage...............................................................90 7.3 UsingaHeaderFileforUserDenedSpecicTaskFunctions...............................91 7.4 Practice7:SpecicTaskFunctions.........................................................93 Solutions........................................................................................95 88.StandardLibraries 8.1 StandardLibraries.........................................................................97 8.2 Practice8:StandardLibraries..............................................................99 Solutions.......................................................................................101 99.CharacterData,Sizeof,Typedef,Sequence 9.1 CharacterDataType......................................................................103 9.2 SizeofOperator...........................................................................104 9.3 Typedef-AnAlias........................................................................105 9.4 SequenceOperator........................................................................106 9.5 Practice9:CharacterData,Sizeof,Typedef,Sequence.....................................107 Solutions.......................................................................................109 1010.IntroductiontoStructuredProgramming 10.1 StructuredProgramming.................................................................111 10.2 PseudocodeExamplesforControlStructures.............................................113 10.3 Flowcharting.............................................................................115 10.4 Practice10:IntroductiontoStructuredProgramming....................................129 Solutions.......................................................................................131 1111.TwoWaySelection 11.1 IfThenElse.............................................................................133 11.2 BooleanDataType......................................................................135 11.3 RelationalOperators.....................................................................136 11.4 CompoundStatement....................................................................137 11.5 Practice11:TwoWaySelection..........................................................138 Solutions.......................................................................................141 1212.MultiwaySelection 12.1 NestedIfThenElse......................................................................143 12.2 LogicalOperators........................................................................146 12.3 CaseControlStructure...................................................................148 12.4 BranchingControlStructures............................................................152 12.5 Practice12:MultiwaySelection..........................................................155 Solutions.......................................................................................159 1313.TestAfterLoops 13.1 DoWhileLoop..........................................................................161 13.2 FlagConcept............................................................................164 13.3 AssignmentvsEqualitywithinC++.....................................................166 13.4 RepeatUntilLoop.......................................................................167 13.5 Practice13:TestAfterLoops............................................................168 Solutions.......................................................................................171 1414.TestBeforeLoops

PAGE 7

v 14.1 IncrementandDecrementOperators.....................................................173 14.2 WhileLoop..............................................................................175 14.3 Practice14:TestBeforeLoops...........................................................180 Solutions.......................................................................................182 1515.CountingLoops 15.1 ForLoop.................................................................................183 15.2 CircularNatureoftheIntegerDataTypeFamily.........................................187 15.3 FormattingOutput.......................................................................189 15.4 NestedForLoops........................................................................191 15.5 Practice15:CountingLoops.............................................................195 Solutions.......................................................................................197 1616.StringClass,UnaryPositiveandNegative 16.1 StringClasswithinC++.................................................................199 16.2 UnaryPositiveandNegativeOperators..................................................201 16.3 Practice16:StringClass,UnaryPostitiveandNegative..................................202 Solutions.......................................................................................205 1717.ConditionalOperatorandRecursion 17.1 ConditionalOperator....................................................................207 17.2 RecursionvsIteration....................................................................208 17.3 Practice17:ConditionalOperatorandRecursion.........................................209 Solutions.......................................................................................212 1818.IntroductiontoArrays 18.1 ArrayDataType........................................................................213 18.2 ArrayIndexOperator....................................................................214 18.3 DisplayingArrayMembers...............................................................215 18.4 Practice18:IntroductiontoArrays......................................................217 Solutions.......................................................................................219 1919.FileI/OandArrayFunctions 19.1 FileInputandOutput...................................................................221 19.2 ArraysandFunctions....................................................................223 19.3 LoadinganArrayfromaFile............................................................224 19.4 MathStatisticswithArrays..............................................................225 19.5 Practice19:FileI/OandArrayFunctions...............................................226 Solutions.......................................................................................228 2020.MoreArrayFunctions 20.1 FindingaSpecicMemberofanArray...................................................229 20.2 SortinganArray.........................................................................230 20.3 Practice20:MoreArrayFunctions.......................................................232 Solutions.......................................................................................234 2121.MoreonTypedef 21.1 VersatileCodewithTypedef.............................................................235 21.2 Practice21:MoreonTypedef............................................................236 Solutions.......................................................................................238 2222.Pointers 22.1 AddressOperator........................................................................239 22.2 ParameterPassingbyReference..........................................................240 22.3 PointerDataType.......................................................................241

PAGE 8

vi 22.4 IndirectionOperator.....................................................................242 22.5 Practice22:Pointers.....................................................................243 Solutions.......................................................................................246 2323.MoreArrays&CompilerDirectives 23.1 MultidimensionalArrays.................................................................247 23.2 ConditionalCompilation.................................................................248 23.3 Practice23:MoreArrays&CompilerDirectives.........................................249 Solutions.......................................................................................251 2424.OOP&HPC 24.1 ObjectOrientedProgramming...........................................................253 24.2 UnderstandingHighPerformanceComputing.............................................254 24.3 Practice24:OOP&HPC................................................................260 Solutions.......................................................................................263 25ReviewMaterials 25.1 Review:FoundationTopicsGroup:1-5...................................................265 25.2 Review:ModularProgrammingGroup:6-9..............................................266 25.3 Review:StructuredProgrammingGroup:10-16..........................................266 25.4 Review:IntermediateTopicsGroup:17-21...............................................267 25.5 Review:AdvancedTopicsGroup:22-24..................................................268 Solutions........................................................................................ ?? 26Appendix 26.1 AbbreviatedPrecedenceChartforC++Operators.......................................269 26.2 C++ReservedKeywords................................................................271 26.3 ASCIICharacterSet.....................................................................272 26.4 ShowHideFileExtensions...............................................................273 26.5 AcademicorScholasticDishonesty.......................................................273 26.6 SuccessfulLearningSkills................................................................275 26.7 StudyHabitsthatBuildtheBrain.......................................................278 Solutions........................................................................................ ?? Glossary ............................................................................................279 Index ...............................................................................................287 Attributions ........................................................................................291

PAGE 9

Preface 1 AboutthisTextbook/Collection ProgrammingFundamentalsAModularStructuredApproachusingC++ ProgrammingFundamentals-AModularStructuredApproachusingC++iswrittenbyKennethLeroy Busbee,afacultymemberatHoustonCommunityCollegeinHouston,Texas.Thematerialsusedinthis textbook/collectionweredevelopedbytheauthorandothersasindependentmodulesforpublicationwithin theConnexionsenvironment.Programmingfundamentalsareoftendividedintothreecollegecourses:Modular/Structured,ObjectOrientedandDataStructures.Thistextbook/collectioncoverstherstofthose threecourses. ConnexionsLearningModules Thelearningmodulesofthistextbook/collectionwerewrittenas standalone modules.Studentsusinga collectionofmodulesasatextbookwillusuallyviewitcontentsbyreadingthemodulessequentiallyas presentedbytheauthorofthecollection. However,themajorityofreadersofthesemoduleswillndthemasaresultofanInternetsearch.The ConnexionsProjectallowstheauthorofamoduletocreateweblinkstootherConnexionsmodulesand Internetlocations.Theselinksareshownwhenviewingmaterialson-lineandarecategorizedintothree types:Example,PrerequisiteandSupplemental.Theimportanceofeachlinkisnumberedfrom1to3by theauthor.Whenviewingthemoduleeachlinksshowsathreepartboxwithyelloworwhiterectangles. Allthreeyellowmeansitisa stronglyrelatedlink .Astheyellowdecreasestheimportancedecreases. Studentsusingthiscollectionforacollegecourseshouldnotethatallofthe Prerequisitelinks within themoduleswillbemodulesthatstudentshouldhavealreadyreadandmostofthe Supplementallinks willbemodulesthatthestudentwillreadshortly.Thus,studentsshouldusePrerequisitelinksforreview asneededandnotbeoverlyconcernedaboutviewingalloftheSupplementallinksattherstreadingof thistextbook/collection. ConceptualApproach Thelearningmodulesofthistextbook/collectionwere,forthemostpart,writtenwithoutconsiderationof aspecicprogramminglanguage.InmanycasestheC++languageisdiscussedaspartoftheexplanation oftheconcept.OftentheexamplesusedforC++areexactlythesamefortheJavaprogramminglanguage. However,somemoduleswerewrittenspecicallyfortheC++programminglanguage.Thiscouldnotbe avoidedastheC++languageisusedinconjunctionwiththistextbook/collectionbytheauthorinteaching collegecourses. 1 Thiscontentisavailableonlineat. 1

PAGE 10

2 BloodshedDev-C++5Compiler/IDE Thisopensourcecompiler/IDEIntegratedDevelopmentEnvironmentwasusedtodevelopthedemonstrationsourcecodelesprovidedwithinthemodulesofthistextbook/collection.Thecompiler/IDEis presentedtothestudentinthesecondmoduleofChapter1,withinstructionsfordownloading,installing andusingthecompiler/IDE.AmorecompleteexplanationoftheIDEalongwithdemonstrationsourcecode listingswitherrorsispresentedinrstmoduleofChapter5.Allofthesourcecodelesprovidedinthis textbook/collectioncontainonlyANSIstandardC++codeandshouldworkonanystandardC++compiler likeMicrosoftVisualStudiowhichincludesC++,MicrosoftVisualC++ExpressorBorlandC++Builder. AboutConnexions ConnexionsModularContent TheConnexionsProjecthttp://cnx.org 2 ispartofthe OpenEducationalResourcesOER movement dedicatedtoprovidinghighqualitylearningmaterialsfreeonline,freeinprintablePDFformat,andat lowcostinboundvolumesthroughprint-on-demandpublishing.Thistextbookisoneofmanycollections availabletoConnexionsusers.Each collection iscomposedofanumberofre-usablelearningmodules writtenintheConnexionsXMLmarkuplanguage.Eachmodulemayalsobere-usedor're-purposed'as partofothercollectionsandmaybeusedoutsideofConnexions. Re-useandCustomization TheCreativeCommonsCCAttributionlicense 3 appliestoallConnexionsmodules.Underthislicense, any Connexionsmodule maybeusedormodiedforanypurposeaslongasproperattributiontothe originalauthorsismaintained.Connexions'authoringtoolsmakere-useorre-purposingeasy.Therefore,instructorsanywherearepermittedtocreatecustomizedversionsofthistextbookbyeditingmodules, deletingunneededmodules,andaddingtheirownsupplementarymodules.Connexions'authoringtools keeptrackofthesechangesandmaintaintheCClicense'srequiredattributiontotheoriginalauthors.This processcreatesanewcollectionthatcanbeviewedonline,downloadedasasinglePDFle,ororderedin anyquantitybyinstructorsandstudentsasalow-costprintedtextbook. Readthebookonline,printthePDF,orbuyacopyofthebook. Tobrowsethistextbookonline,visitthecollectionhomepage.Youwillthenhavethreeoptions. 1.Youmayviewthecollectionmoduleson-linebyclickingonthe"Start "link,whichtakesyouto therstmoduleinthecollection.Youcanthennavigatetothenextmoduleusing"NEXT "and throughthesubsequentmodulesbyusingthe" PREVIOUS|NEXT "buttonthatistowards theupperrighttomoveforwardandbackwardinthecollection.Youcanjumptoanymoduleinthe collectionbyclickingonthatmodule'stitleinthe"TABLEOFCONTENTS"boxontheleftsideof thewindow.Ifthesecontentsarehidden,makethemvisiblebyclickingonthesmalltriangletothe rightofthe"TABLEOFCONTENTS".Chaptersalsohaveasmalltriangletoshoworhidecontents. 2.YoumayobtainaPDFoftheentiretextbooktoprintorviewoinebyclickingonthe"Download PDF"linkinthe"ContentActions"box. 3.Youmayorderaboundcopyofthecollectionforareasonableprintingandshippingfeebyclicking onthe"Orderprintedcopy"button. 2 http://cnx.org/ 3 http://creativecommons.org/licenses/by/2.0/

PAGE 11

3 ConnexionsPDFConversionProblems Buyingacopyofthetextbook/collectionisbasicallysendingthePDFletoaprintingservicethathas acontractwiththeConnexionsproject.ThereareseveralknownprintingproblemsandtheConnexions Projectisawareofthemandseekingasolution.Inthemeantime,beawarethatquirksexistforprinted PDFmaterials.Adescriptionoftheknownproblemsare: 1.Whenitconvertsan"Example"thePDFdisplaystherstlineofanexampleproperlybutindents theremaininglinesoftheexample.Thisproblemoccursfortheprintingofabookbecauseitprints aPDFanddownloadingeitheramoduleoratextbook/collectionasaPDF. 2.Chapternumberinghasbeenaddedtotheon-lineTableofContents.Thiswillmakeiteasierfor studentstoquicklygettothechapterreadingmaterials.Howeverthiscreatesa"double"chapter numberingwithinthetextbook/collection'sPDFandcustomprintingformats. 3.WithinC++therearethreeoperatorsthatdonotconvertproperlytoPDFformat. decrement whichistwominussigns insertion whichistwolessthansigns extraction whichistwogreaterthansigns Table1

PAGE 12

4

PAGE 13

AuthorAcknowledgements 4 Iwishtoacknowledgethemanypeoplewhohavehelpedmeandhaveencouragedmeinthisproject. 1.Mr.AbassAlamnehe,whoisafellowfacultymemberatHoustonCommunityCollege.HehasencouragedtheuseofConnexionsasan"opensource"publishingconcept.Hiscommentsonseveralmodules haveleddirectlytotheimprovementofthematerialsinthistextbook/collection. 2.ThehundredsmostlikelyathousandplusstudentsthatIhavetakenprogrammingcoursesthatI havetaughtsince1984.Thelanguagesinclude:COBOL,mainframeIBMassembly,Intelassembly, Pascal,"C"and"C++".TheyhaveoftensuggestedthatIwritemyownbookbecausetheythought thatIwasexplainingthesubjectmatterbetterthantheauthorofthetextbookthatwewereusing. Littledidmystudentsunderstandthatdirectlyorindirectlytheyaidedintheimprovementofthe materialsfromwhichItaughtaswellasimprovingmeasateacher. 3.Tomyfuturestudentsandallthosethatwillusethistextbook/collection.Theywillprovidesuggestions forimprovementaswellasbeingthethousandeyesidentifyingthehardtondtypos,etc. 4.Mywife,Carol,whosupportsmeinallthatIdo.ShehastoleratedthemanyhoursthatIhavespent inconcentrationondevelopingthemodulesthatcomprisethiswork.Withouthersupport,thiswork wouldnothavehappened. 4 Thiscontentisavailableonlineat. 5

PAGE 14

6

PAGE 15

OrientationandSyllabus 5 Orientation Textbook/CollectionLayout Theapproachofthiscoursewillbetotakethestudentthroughaprogressionofmaterialsthatwillallow thestudenttodeveloptheskillsofprogramming.ThebasicunitofstudyisaConnexionsmodule.Several modulesarecollectedintoachapter.Thechaptersaredividedintovegroups. GroupTitle Chapters Modules Pre-ChapterItems N/A 3 FoundationTopics 1-5 27 ModularProgramming 6-9 17 StructuredProgramming 10-16 30 IntermediateTopics 17-21 17 AdvancedTopics 22-24 11 ReviewMaterials N/A 5 Appendix N/A 7 TotalModules N/A 117 Table1 Someprofessorsusingthistextbook/collectionmightdecidetoeliminatecertainmodulesorchapters. SomemayeliminatetheentireAdvancedTopicsgroup.Otherprofessorsmaychoosetoaddadditionalstudy materials.Theadvantageofthistextbook/collectionisthatitmaybeadaptedbyprofessorstosuitthe needsoftheirstudents. ChapterLayout Eachchapterwillusuallyowfrom: 1.OneormoreConnexionsmodulesbuiltforindependentdelivery. 2.AConnexionsPracticemodulebuiltspecicallyforthistextbook/collection. AsyouproceedwiththeConnexionsmodulesthatcompriseachapter,youshould: Completeanytasks/demosthatrequiredownloadingitems. 5 Thiscontentisavailableonlineat. 7

PAGE 16

8 Doanyexercises. Create3x5studycardsforalldenitions.Whenthismaterialisusedasatextbookforacoursethe denitionsaretobememorized.Conrmthiswithyourprofessor. AsyoustartthePracticemoduleyouwillusuallyencounter: LearningObjectives MemoryBuildingActivitiesakaMBAsLinkThesecouldconsistofanyofthefollowingtypesof interactivecomputeractivities:ashcard,crosswordpuzzle,seekaword,dragndrop,labeling, orderingorsorting.Whenthematerialsareusedasatextbookforacourse,itisimperativethat studentsdoavarietyofrepetitiveactivitiesinordertomemorizebasiccoursematerial.Besides,have funlearning. ExercisesInadditiontoanyexerciseswithinthestudymodulesthatyoucompletedbeforethe practicemodule,therewillbeatleastoneexerciseforstudentstocomplete. MiscellaneousItemsThesewillexistforsomeofthechapters. LabAssignmentUsually,completedonone'sowneorts.Reviewtheinstructions/restrictionsfrom yourprofessor/teacherifusingthisforahighschoolorcollegecreditcourse. ProblemsTheintentofthisactivityisforstudentstoformulatetheirownanswers.Thus,solutions totheproblemswillnotbeprovided.Whenthematerialsareusedasatextbookforacourse,the professor/teachermayassignstudentstoa"StudyGroup"orletstudentsformstudygroupstodiscuss theirsolutionswitheachother.Ifyouareusingthisforahighschoolorcollegecreditcourse,verifythat youmayworkasteamatsolvingtheproblems.Thistypeofapprovedactivityiscalled"authorized collusion"andisnotaviolationof"AcademicorScholasticDishonesty"rules. Aprofessorusingthistextbook/collection/coursewillmostlikelyhaveadditionallabassignments,quizzes andexamsthatwouldbeusedincalculatingyourgrade. ConnexionsModuleReadingList Themodulesinthistextbook/collectionhavehadcontentreviewedandarebelievedtobesucient,thus no additionaltextbookisrequired .However,somestudentsdesireadditionalreferencesorreading.The authorhasusedseveraltextbooksovertheyearsforteaching"COSC1436ProgrammingFundamentalsI" courseatHoustonCommunityCollege.Areadingreferencelisthasbeenpreparedandincludesreferences forthefollowingtextbooks: 1.StartingOutwithC++EarlyObjects,by:TonyGaddiset.al.,6 th Edition,ISBN:0-321-51238-3 2.StartingOutwithC++EarlyObjects,by:TonyGaddiset.al.,5 th Edition,ISBN:0-321-38348-6 3.ComputerScienceAstructuredApproachusingC++,by:BehrouzA.Forouzanet.al.,2 nd Edition, ISBN:0-534-37480-8 Thesetextbooksaretypicallyavailableintheusedtextbookmarketatareasonableprice.Youmayuse anyoneofthethreebooks.Ifyouacquireoneoftheabove optional traditionaltextbooks,youmaywant todownloadandstorethefollowingletoyourstoragedevicediskdriveorashdriveinanappropriate folder. DownloadfromConnexions:Connexions_Module_Reading_List_col10621.pdf 6 Syllabus Thesyllabusforacoursethatisforcreditwillbeprovidedbyyourspeciccourseprofessor.Ifyouareusing thistextbook/collectionfornon-creditasself-study,wehavesomesuggestions: 6 Seetheleat

PAGE 17

9 1.Planregularstudyperiods 2.ReviewthethreePre-ChapterItemsmodules 3.ReviewthelastfourmodulesintheAppendix 4.ProceedwithChapter1goingthroughall24chapters 5.Doallofthedemoprogramsasyouencounterthem 6.Memorizeallofthetermsanddenitions 7.Doalllabassignments 8.PrepareanswerstoalloftheproblemsinthePracticemodules 9.Attheendofeverysection,dotheReviewmodule Theseisnomagicwaytolearnaboutcomputerprogrammingotherthantoimmerseyourselfintoregular studyand studyincludesmorethancasualreading .Tohelpyoukeeptrackofyourstudy,wehave includedacheckolistforthetextbook/collection. Check Description #Modules Pre-ChapterItems 3 LastfourAppendixItems 4 Chapters1to5 27 ReviewMaterialsfor1to5 1 Chapters6to9 17 ReviewMaterialsfor6to9 1 Chapters10to16 30 ReviewMaterialsfor10to16 1 Chapters17to21 17 ReviewMaterialsfor17to21 1 Chapters22to24 11 ReviewMaterialsfor22to24 1 FirstthreeAppendixItems 3 N/A TotalModules 117 Table2

PAGE 18

10

PAGE 19

Chapter1 1.IntroductiontoProgramming 1.1SystemsDevelopmentLifeCycle 1 1.1.1Discussion The SystemsDevelopmentLifeCycle isthebigpictureofcreatinganinformationsystemthathandles amajortaskreferredtoasanapplication.The applications usuallyconsistofmanyprograms.An examplewouldbetheDepartmentofDefensesupplysystem,thecustomersystemusedatyourlocalbank, therepairpartsinventorysystemusedbycardealerships.Therearethousandsofapplicationsthatusean informationsystemcreatedjusttohelpsolveabusinessproblem. Anotherexampleofaninformationsystemwouldbethe"101ComputerGames"softwareyoumightbuy atanyofseveralretailstores.Thisisanentertainmentapplication,thatisweareapplyingthecomputer todoataskentertainyou.Thesoftwareactuallyconsistsofmanydierentprogramscheckers,chess,tic tactoe,etc.thatweremostlikelywrittenbyseveraldierentprogrammers. Computerprofessionalsthatareinchargeofcreatingapplicationsoftenhavethejobtitleof System Analyst .Themajorstepsincreatinganapplicationincludethefollowingandstartat Planning step. 1 Thiscontentisavailableonlineat. 11

PAGE 20

12 CHAPTER1.1.INTRODUCTIONTOPROGRAMMING Figure1.1: SystemsDevelopmentLifeCycle Duringthe Design phasetheSystemAnalystwilldocumenttheinputs,processingandoutputsofeach programwithintheapplication.Duringthe Implementation phaseprogrammerswouldbeassignedto writethespecicprogramsusingaprogramminglanguagedecidedbytheSystemAnalyst.Oncethesystem ofprogramsistestedthenewapplicationisinstalledforpeopletouse.Astimegoesby,thingschangeanda specicpartorprogrammightneedrepair.Duringthe Maintenance phase,itgoesthroughaminiplanning, analysis,designandimplementation.Theprogramsthatneedmodicationareidentiedandprogrammers changeorrepairthoseprograms.Afterseveralyearsofuse,thesystemusuallybecomesobsolete.Atthis pointamajorrevisionoftheapplicationisdone.Thusthecyclerepeatsitself. 1.1.2Denitions Denition1.1:systemanalyst Computerprofessionalinchargeofcreatingapplications. Denition1.2:applications Aninformationsystemorcollectionofprogramsthathandlesamajortask. Denition1.3:lifecycle SystemsDevelopmentLifeCycle:Planning-Analysis-Design-Implementation-Maintenance

PAGE 21

13 Denition1.4:implementation ThephaseofaSystemsDevelopmentLifeCyclewheretheprogrammerswouldbeassignedtowrite specicprograms. 1.2BloodshedDev-C++5Compiler/IDE 2 1.2.1Introduction MicrosoftandBorlandarethetworeputablenameswithintheprogrammingworldforcompilers.Theysell compilersoftwareformanyprogramminglanguages.FortheC++programminglanguage,theMicrosoft VisualStudiowhichincludesC++andBorlandC++Builderareexcellentcompilers.Oftenwithtextbooks orfreeviatheinternet;youcangetMicrosoft'sVisualC++ExpressorBorland'sPersonalEditionversion ofacompiler.However,installingeitherofthesecomplierscanbecomplex.Microsoft'sVisualStudio compileroftencreatesavarietyofinstallationproblemssuchasmakingsuretheoperatingsystemand.net componentsarecurrentthusmakingitdicultforstudentstoinstallathome.Thesecompliersrequire youtobuildaprojecttoencompasseveryprogram.Usingacommerciallysoldcompilerthatprofessional programmerswouldconsiderusingforprojectdevelopmentisneforprofessionalsbutoftenconfusingto beginners.Eventually,ifyouaregoingtobecomeaprofessionalprogrammer,youwillneedtobecome familiarwiththecommerciallysoldcompilers. Wesuggestthatbeginningstudentsconsideroneoftheeasiertoinstallcompilersoftwarepackagesforuse inaprogrammingfundamentalscourse.Thebestoptionwehavefoundisan opensource compiler/IDE IntegratedDevelopmentEnvironmentnamed: BloodshedDev-C++5compiler/IDE Denition1.5:opensource Groupdevelopmentofsourcecodeforsoftwarethatismadeavailabletothepublicatnocost. 1.2.2BloodshedDev-C++5compiler/IDE Advantages:CanbeinstalledonWindows95/98/NT/2000/XPoperatingsystems.Ihaveitinstalledon WindowsVistaoperatingsystem,thusitcanworkwithslowerprocessorsandalmostanyWindowsoperating system.Itonlyrequiresabout80MBofstoragespaceusuallyenoughforthecompilerwithallofitsles andstorageroomforseveralofyourprograms.Itisveryeasytoinstallandeasytouse.Doesnotrequire theuseofa"project";thusindividualsourcecodelescanbeeasilycompiled. Disadvantages:Wouldnotnormallybeusedbyprofessionalprogrammers,butissucientforabeginning computerprogrammingcourseandisafull-featuredcompiler/IDE. UniqueAdvantage: Canbeinstalledandrunonaashdrive,thusgivingthestudenttheabilityto workontheirlabassignmentsonanycomputerthathasaUSBport.Thiscangivethestudent portability beingabletodolabassignmentsathome,work,library,openlab,classroom,friend'shouse,etc. Denition1.6:portability Theabilitytotransportsoftwareonaashdriveandthususeitonvariousmachines. 1.2.3PreparationbeforeInstallation 1.2.3.1CreatingtheNeededFoldersandSub-Folders Youneedtogetthe software andaC++ sourcecode programthathasbeentestedandiserrorfree. Youwillneedabout80MBofstoragespace.Wesuggestthatyoucreate twofolders onyourharddriveor ashdrivedependingonwhichinstallationyouchoose.Ifonaashdrivecreatethemattherootlevelof thedrive.Ifonyourhomemachine,youcanusethefolderareasetupbytheoperatingsystemforyouasa user.Namethem: 2 Thiscontentisavailableonlineat.

PAGE 22

14 CHAPTER1.1.INTRODUCTIONTOPROGRAMMING Cpp_Software_Download Cpp_Source_Code_Files WithintheCpp_Source_Code_Filesfolder,createasub-foldernamed: Compiler_Test Tohelpyoukeeplesorganized,youwillwanttocreateothersub-foldersforstoringsourcecodeles.We suggestyoucreateatleasttwoothersub-foldertobeusedwithConnexions'relatedmodules.Withinthe Cpp_Source_Code_Files,createsub-foldersnamed: Demo_Programs Monitor_Header Denition1.7:folder Anamedareaforstorageofdocumentsorotherlesonadiskdriveorashdrive. Denition1.8:sourcecode Anycollectionofstatementsordeclarationswritteninsomehuman-readablecomputerprogramminglanguage. 1.2.3.2GettingtheSoftware Thefullversionofthesoftwareisnamed:Dev-C++5.0beta9.2.9.9.2.0MBwithMingw/GCC 3.4.2YoucaneitherdownloaditfromBloodshedordownloadtheversionasof12/8/2008thatisstored ontheConnexionswebsite.StoreitintheCpp_Software_Downloadfolderyoucreated.Thesoftwareis approximately9.1MBandwilltakeseveralminutestodownloadifyouareusingadial-upmodemconnection. tip: Thesoftwarehasnotsignicantlychangedsince2007andtheConnexionsversionwillbe sucientformostusers.TheBloodshedlinkrequiressomeadditionalnavigationtogettothe softwaredownload.Thus,becauseitissignicantlyeasier,werecommendthatyoudownloadthe softwarefromtheConnectionswebsite. LinktoBloodshed:http://www.bloodshed.net/dev/devcpp.html 3 DownloadfromConnexions:devcpp-4.9.9.2_setup.exe 4 1.2.3.3GettingaC++SourceCodeFile ListedbelowisaC++sourcecodeletitled:Compiler_Test.cppIthasbeenpreparedforConnexionsweb delivery.DownloadandstoreitintheCompiler_Testsub-folderyoucreated.Youmayneedtorightclick onthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Compiler_Test.cpp 5 1.2.4InstallationInstructionsforBloodshedDev-C++5compiler/IDE TheVersion5whichiswelltesteddon'tletthebetareleasescareyouandshouldworkonavarietyof machinesandvariousMicrosoftOperatingsystemsincludingWindows98,Windows2000,WindowsXPand WindowsVista.Belowareinstallationinstructionsforinstallingitonamachineorinstallingitonaash drive.Wedon'tsuggesttryingtoswitchbetweenthemachinedriveandashdrive.Ifitisinstalledon themachinedriveandyoutryinstallingitonaashdrive,itcreatesproblemsandwillnotworkperperly. Eitherinstallitontheashdrivetogainyourportabilityorinstallitonyourmachine. 3 http://www.bloodshed.net/dev/devcpp.html 4 Seetheleat 5 Seetheleat

PAGE 23

15 1.2.4.1ComputerInstallationInstructions 1.NavigatetotheCpp_Software_Downloadfolderandrunthe devcpp-4.9.9.2_setup.exe software bydoubleclikingonthelename. 2.Usecommonsenseandanswertheinstallationprompts.NOTETHEFOLLOWINGTWOITEMS: 3.Whenitgetstothe"ChooseInstallLocation"usethedefaultsoftwarelocationof: C: n Dev-Cpp n or selectthelocationyouwanttostoretheinstalledprogrambutusethedefaultunlessyouarefamiliar withinstallingsoftware. 4.Whenitasks:"DoyouwanttoinstallDevC++forallusersonthiscomputer?"answer"Yes". 5.Afteritinstalls,itwillasksome"rsttimeconguration"questions.Again,usecommonsenseand answerthequestions.NOTETHEFOLLOWINGITEM: 6.Answer"No"totheretrieveinformationfromheaderles. 7.Itwillstartyourcompiler/IDEwitha"Tipoftheday".Wesuggestyouchecktheboxinthelower leftandselect"Close". 8.Closeyourcompiler/IDEbyusingthenormalred"X"box.Wewanttoshowyouhowtostartyour compillernormally. 9.Youstartyourcompilersoftwaresimilartostartinganysoftwareloadedonyourmachine"Start"then "AllPrograms"then"BloodshedDev-C++"then"Dev-C++". 10.OnthemenusatthetopSelect"File"then"Openprojectorle"thennavigatetowhereyoursource codeleCompiler_Test.cppisstoredonyourharddrive.Seethesuggestedfoldernameabove. Selectthesourcecodeleandopenit. 11.Youshouldseethesourcecodelisting.PressF9keyorselectthe"Execute"then"Compile&Run" fromthemenusatthetop.Ablackscreenboxshouldappearandyouanswerquestionsappropriately toruntheprogram.Whenyouaredonerunningyourprogramtheblackscreenboxgoesaway. 1.2.4.2FlashDriveInstallationInstructions 1.NavigatetotheCpp_Software_Downloadfolderandrunthe devcpp-4.9.9.2_setup.exe software bydoubleclikingonthelename. 2.Usecommonsenseandanswertheinstallationprompts.NOTETHEFOLLOWINGTWOITEMS: 3.Whenitgetstothe"ChooseInstallLocation"youcanseethatthedefaultsoftwarelocationof: C: n Dev-Cpp n however,itneedstobechanged.Changethe"DestinationDirectory"byselecting changingthedefaultsoftwarelocationfrom: C: n Dev-Cpp n to DriveLetter: n Dev-Cpp n wherethe DriveLetter isthedrivethatrepresentsyourashdrive. 4.Whenitasks:"DoyouwanttoinstallDevC++forallusersonthiscomputer?"answer"No". 5.Afteritinstalls,itwillasksome"rsttimeconguration"questions.Again,usecommonsenseand answerthequestions.NOTETHEFOLLOWINGITEM: 6.Answer"No"totheretrieveinformationfromheaderles. 7.Itwillstartyourcompiler/IDEwitha"Tipoftheday".Wesuggestyouchecktheboxinthelower leftandselect"Close". 8.Closeyourcompiler/IDEbyusingthenormalred"X"box.Wewanttoshowyouhowtostartyour compillernormally. 9.Tostartyourcompilersoftwareyounavigatetothe"Dev-Cpp"folderonyourashdriveandselectthe "devcpp.exe"application.NOTE:Whenusingtheashdriveyoushouldnottrystartingthecompiler bydoubleclickingonaC++sourcecodele.Thismethodworksonamachineinstallationbutdoes notworkonaashdriveinstallation. 10.OnthemenusatthetopSelect"File"then"Openprojectorle"thennavigatetowhereyoursource codeleCompiler_Test.cppisstoredonyourashdrive.Seethesuggestedfoldernameabove. Selectthesourcecodeleandopenit. 11.Youshouldseethesourcecodelisting.PressF9keyorselectthe"Execute"then"Compile&Run" fromthemenusatthetop.Ablackscreenboxshouldappearandyouanswerquestionsappropriately toruntheprogram.Whenyouaredonerunningyourprogramtheblackscreenboxgoesaway.

PAGE 24

16 CHAPTER1.1.INTRODUCTIONTOPROGRAMMING 1.3ModularizationandC++ProgramLayout 6 1.3.1ConceptofModularization Oneofthemostimportantconceptsofprogrammingistheabilitytogroupsomelinesofcodeintoaunit thatcanbeincludedinourprogram.Theoriginalwordingforthiswasasub-program.Othernamesinclude: macro,sub-routine,procedure,moduleandfunction.Wearegoingtousetheterm function forthatis whattheyarecalledinthetwopredominantprogramminglanguagesoftoday:C++andJava.Functions areimportantbecausetheyallowustotakelargecomplicatedprogramsandtodividethemintosmaller manageablepieces.Becausethefunctionisasmallerpieceoftheoverallprogram,wecanconcentrateon whatwewantittodoandtestittomakesureitworksproperly.Generallyfunctionsfallintotwocategories: 1. ProgramControl -Functionsusedtosimplysubdivideandcontroltheprogram.Thesefunctionsare uniquetotheprogrambeingwritten.Otherprogramsmayusesimilarfunctionsmaybeevenfunctions withthesamename,butthecontentofthefunctionsarealmostalwaysverydierent. 2. SpecicTask -Functionsdesignedtobeusedwithseveralprograms.Thesefunctionsperforma specictaskandthusareuseableinmanydierentprogramsbecausetheotherprogramsalsoneed todothespecictask.Specictaskfunctionsaresometimesreferredtoasbuildingblocks.Because theyarealreadycodedandtested,wecanusethemwithcondencetomoreecientlywritealarge program. Themainprogrammustestablishtheexistenceoffunctionsusedinthatprogram.Dependingonthe programminglanguage,thereisaformalwayto: 1.deneafunctionit's denition orthecodeitwillexecute 2. call afunction 3.declareafunctiona prototype isadeclarationtoacomplier ProgramControlfunctionsnormallytodonotcommunicateinformationtoeachotherbutuseacommon areaforvariablestorage.SpecicTaskfunctionsareconstructedsothatdatacanbecommunicatedbetween thecallingprogrampiecewhichisusuallyanotherfunctionandthefunctionbeingcalled.Thisabilityto communicatedataiswhatallowsustobuildaspecictaskfunctionthatmaybeusedinmanyprograms. Therulesforhowthedataiscommunicatedinandoutofafunctionvarygreatlybyprogramminglanguage, buttheconceptisthesame.Thedataitemspassedorcommunicatedarecalledparameters.Thusthe wording: parameterpassing .Thefourdatacommunicationoptionsinclude: 1.nocommunicationinwithnocommunicationout 2.somecommunicationinwithnocommunicationout 3.somecommunicationinwithsomecommunicationout 4.nocommunicationinwithsomecommunicationout 1.3.2IntroductionofFunctionswithinC++ Wearegoingtoconsiderasimpleprogramthatmightbeusedfortestingacompilertomakesurethatitis installedcorrectly. Example1.1:Compiler_Test.cppsourcecode //****************************************************** //Filename:Compiler_Test.cpp 6 Thiscontentisavailableonlineat.

PAGE 25

17 //Purpose:Averagetheagesoftwopeople //Author:KenBusbee; KennethLeroyBusbee //Date:Jan5,2009 //Comment:Mainideaistobeableto //debugandrunaprogramonyourcompiler. //****************************************************** //HeadersandOtherTechnicalItems #include < iostream > usingnamespacestd; //FunctionPrototypes voidpausevoid; //Variables intage1; intage2; doubleanswer; //****************************************************** //main //****************************************************** intmainvoid { //Input cout n nEntertheageofthefirstperson--> :"; cin age1; cout n nEntertheageofthesecondperson-> :"; cin age2; //Process answer=age1+age2/2.0; //Output cout n nTheaverageoftheiragesis-------> :"; cout answer; pause; return0; } //****************************************************** //pause //****************************************************** voidpausevoid {

PAGE 26

18 CHAPTER1.1.INTRODUCTIONTOPROGRAMMING cout n n n n"; system"PAUSE"; cout n n n n"; return; } //****************************************************** //EndofProgram //****************************************************** Thisprogramhastwofunctions,onefromeachofourcategories.Thetechnicallayoutoffunctionsarethe same,itisourdistinctionthatcreatesthetwocategoriesbasedonhowafunctionisbeingimplemented. 1.3.2.1ProgramControlFunction ThemainprogrampieceinC++programisaspecialfunctionwiththe identiername ofmain.The specialoruniquenessofmainasafunctionisthatthisiswheretheprogramstartsexecutingcodeandthisis whereitusuallystopsexecutingcode.Itisusuallytherstfunctiondenedinaprogramandappearsafter theareausedforincludes,othertechnicalitems,declarationofprototypes,thelistingofglobalconstants andvariablesandanyotheritemsgenerallyneededbytheprogram.Thecodetodenethefunctionmain isprovided;however,itisnotprototypedorusuallycalledlikeotherfunctionswithinaprogram.Inthis simpleexample,therearenootherprogramcontrolfunctions. 1.3.2.2SpecicTaskFunction Weoftenhavetheneedtoperformaspecictaskthatmightbeusedinmanyprograms.IntheCompile_Test.cppsourcecodeabovewehavesuchataskthatisusedtostoptheexecutionofthecodeuntilthe userhitstheenterkey.Thefunctionsnameis:pause.Thisfunctionisnotcommunicatinganyinformation betweenthecallingfunctionanditself,thustheuseofthedatatypevoid. Example1.2:generallayoutofafunction < returnvaluedatatype > functionidentifiername < datatype >< identifiernameforinputvalue > { linesofcode; return < value > ; } Thereisnosemi-colonaftertherstline.Semi-colonsareusedattheendofastatementinC++,butnot ontherstlinewhendeningafunction.Functionshaveasetof braces {}usedforidentifyingagroupor blockofstatementsorlinesofcode.Therearenormallyseverallinesofcodewithinafunction.Linesofcode containingtheinstructionsendinasemi-colon.Canyouidentifythedenitionofthepausefunctioninthe aboveprogramexample?Thepausefunctiondenitionisafterthefunctionmain.Thoughnottechnically required,mostprogramslistallfunctionsprogramcontrolorspecictaskafterthefunctionmain. Let'sidentifythelocationwherethefunctionpauseiscalled.Thecallingfunctionisthefunctionmain andittowardstheendofthefunction.Thelinelookslike: pause; Whenyoucallafunctionyouuseitsidentiernameandasetofparentheses.Youplaceanydataitems youarepassinginsidetheparentheses,andinourexampletherearenone.Asemi-colonendsthestatement

PAGE 27

19 orlineofcode.Afterourprogramiscompiledandrunning,thelinesofcodeinthefunctionmainare executedandwhenitgetstothecallingofthepausefunction,thecontroloftheprogrammovestothepause functionandstartsexecutingthelinesofcodeinthepausefunction.Whenit'sdonewiththelinesofcode, itwillreturntotheplaceintheprogramthatcalleditinourexamplethefunctionmainandcontinue withthecodeinthatfunction. Onceweknowhowtodeneafunctionandhowtocallafunction,weusuallywillneedtoknowhowto declareafunctiontothecompilercalledaprototype.Becauseofnormalcomputerprogrammingindustry standards,programmersusuallylistthefunctionmainrstwithotherfunctionsdenedafterit.Then somewhereinthefunctionmain,wewillcallafunction.Whenweconvertoursourcecodeprogramtoan executableversionforrunningonourcomputer,therststepoftheprocessiscompiling.Thecompiler programdemandstoknowwhatthecommunicationwillbebetweentwofunctionswhenafunctioniscalled. Itwillknowthecommunicationwhatgoinginandoutasparametersifthefunctionbeingcalledhasbeen dened.But,wehavenotdenedthatfunctionyet;itisdenedafterthefunctionmain.Tosolvethis problem,weshowthecompileraprototypeofwhatthefunctionwilllooklikeatleastthecommunication featuresofthefunctionwhenwedeneit. voidpausevoid; Thislineofcodelooksexactlyliketherstlineinourfunctiondenitionwithoneimportantaddition ofasemi-colon.Prototypesordeclarationstothecompilerofthecommunicationsofafunctionnotyet denedareplacednearthetopoftheprogrambeforethefunctionmain. Summaryconcept:Ifyoucall afunctionbeforeitisdenedyoumustprototypeitbeforeitiscalled. Lookingatourlistofthe threethingsyoudoinconjunctionwithafunctionintheorderthattheynormallyappearinaprogram, thereisaformalwayto: 1.declareafunctionaprototypeisacommunicationsdeclarationtoacomplier 2.callafunction 3.deneafunction 1.3.3C++ProgramLayout Fromtheaboveexample,youcanseethat2/3oftheprogramisthetwofunctions.MostC++programs haveseveralitemsbeforethefunctionmain.Asintheexample,theyoftenare: 1.DocumentationMostprogramshaveacommentareaatthestartoftheprogramwithavariety ofcommentspertinenttotheprogram.Anylinestartingwithtwoslashes//isacommentandthe compilersoftwaredisregardseverythingfromthe//totheendoftheline. 2.#include < iostream > Thislineofcodeinsertsaleintothesourcecode.Thelecontainsnecessary codetobeabletodosimpleinputandoutput. 3.usingnamespacestdTheC++compilerhasanareawhereitkeepstheidentiernamesusedina programorganizedanditiscalledanamespace.Thereisanamespacecreatedinconjunctionwiththe iostreamlecalled:std.Thislineinformsthecompilertousethenamespacestdwheretheidentier namesintheiostreamareestablished. 4.Functionprototypeshavealreadybeenexplained. 5.Weneedsomevariablesstorageareasforthisprogramtowork.Theyaredenednext. 1.3.4Denitions Denition1.9:modularization Theabilitytogroupsomelinesofcodeintoaunitthatcanbeincludedinourprogram. Denition1.10:function Whatmodulesarecalledinthetwopredominantprogramminglanguagesoftoday:C++andJava.

PAGE 28

20 CHAPTER1.1.INTRODUCTIONTOPROGRAMMING Denition1.11:programcontrol Functionsusedtosimplysubdivideandcontroltheprogram. Denition1.12:specictask Functionsdesignedtobeusedwithseveralprograms. Denition1.13:parameterpassing Howthedataiscommunicatedintoandoutofafunction. Denition1.14:identiername Thenamegivenbytheprogrammertoidentifyafunctionorotherprogramitemssuchasvariables. Denition1.15:functionprototype Afunction'scommunicationsdeclarationtoacomplier. Denition1.16:functioncall Afunction'susingorinvokingofanotherfunction. Denition1.17:functiondenition Thecodethatdeneswhatafunctiondoes. Denition1.18:braces UsedtoidentifyablockofcodeinC++. 1.4Practice1:IntroductiontoProgramming 7 1.4.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.InstalltheBloodshedDev-C++5compiler 3.Makeminormodicationstoanexistingprogram 1.4.2MemoryBuildingActivities Linkto:MBA01 8 1.4.3Exercises Exercise1.1 Solutiononp.23. Answerthefollowingstatementsaseithertrueorfalse: 1.BeginningprogrammersparticipateinallphasesoftheSystemsDevelopmentLifeCycle. 2.TheBloodshedDev-C++5compiler/IDEisthepreferredcompilerforthistextbook/collection,howeveranyC++compilerwillwork. 3.Mostcompilerscanbeinstalledonaashdrive. 4.Inadditiontofunctionasthenameofasub-program,thecomputerindustryalsousesmacro, procedureandmodule. 5.Generallyfunctionsfallintotwocategories:ProgramControlandSpecicTask. 7 Thiscontentisavailableonlineat. 8 Seetheleat

PAGE 29

21 1.4.4MiscellaneousItems Noneatthistime. 1.4.5LabAssignment 1.4.5.1CreatingaFolderorSub-FolderforChapter01Files WithintheChapter1Connexionsmodulesyouweregivendirectionsonhowtoinstallthe Bloodshed Dev-C++5compiler/IDE andtotestyourinstallationwiththeCompiler_Test.cppsourcecodele.If youhavenotdonethis,returntotheConnexionsmaterialsandcompletethistask. Inthecompilerinstallationdirectionsyouwereaskedtomakeafoldernamed:Cpp_Source_Code_Files. Allofyourlabassignmentsinthiscourseassumeyouhavethatfolderonthesamedriveasyourcompiler eitherdriveC:yourharddiskdrive,oronaashdrive.Ifyoudon'thavethatfolder,gocreateitnow. Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_01withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 1.4.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Compiler_Test.cpp 9 1.4.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. Navigatetoyoursub-folder:Chapter_01andrenametheCompiler_Test.cppsourcecodeleto: Lab_01.cpp Ifyouarehavingproblemsseeingtheleextensions,visittheShowHideFileExtensionsinstructions withintheAppendix. Startyourcompilerandopenthesourcecodele.Carefullymakethefollowingmodications: Changethecommentsatthetop,specically: Thelenameshouldbe:Lab_01.cpp Purposeshouldbe:Averagetheweightofthreepeople Author:putyournameanderasemynameandcopyright Date:Puttoday'sdate Removethenext2linesofcommentsdon'terasetheasteriskline NOTE:Duringtherestofthecourseyouwilloftenuseasourcecodeleprovidedbytheinstructor asyourstartingpointforanewlabassignment.Sometimesyouwilluseasourcecodelethatyou havecreatedasyourstartingpointforanewlabassignment.Eitherway,youshouldmodifythe commentsasappropriatetoincludeataminimumthefourlinesofinformationasestablishedinthis labassignment. 9 Seetheleat

PAGE 30

22 CHAPTER1.1.INTRODUCTIONTOPROGRAMMING Wearenowgoingtomakesimplemodicationstothisprogramsothatitisableto averagetheweightofthreepeople.Dothefollowing: Withinthevariablesarea,changethevariablenamesforage1andage2toweight1andweight2.Add anothervariableofintegerdatatypewiththeidentiernameofweight3. Theinputareahastwopromptsandrequestsfordatafromtheuser.Theyarepairedupaprompt andgettingdatafromthekeyboard.Weneedtomodifytheprompttoaskforweightinsteadofage. Weneedtochangethevariablenamefromage1toweight1.Dothisforthesecondpairthatprompts andgetstheseconddataitem.Createathirdpairthatpromptsandgetsthethirddataitem. Theprocessareahasonlyonelineofcodeandweneedtomakechangesthataddtheweight3and dividesby3.0insteadof2.0.Thecodeshouldlooklikethis: answer=weight1+weight2+weight3/3.0; Theoutputareaneedsthetextmodiedfromagestoweights. Buildcompileandrunyourprogram.Youhavesuccessfullywrittenthisprogramifwhenitrunand youputinthethreeweights;ittellsyouthecorrectaverage. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 1.4.6Problems 1.4.6.1Problem01aInstructions ListthestepsoftheSystemsDevelopmentLifeCycleandindicatewhichstepyouarelikelytoworkinasa newcomputerprofessional.

PAGE 31

23 SolutionstoExercisesinChapter1 SolutiontoExercise1.1p.20 Answers: 1.false 2.true 3.false 4.true 5.true

PAGE 32

24 CHAPTER1.1.INTRODUCTIONTOPROGRAMMING

PAGE 33

Chapter2 2.ProgramPlanning&Design 2.1ProgramDesign 1 2.1.1TopicIntroduction ProgramDesignconsistsofthestepsaprogrammershoulddobeforetheystartcodingtheprogramina speciclanguage.Thesestepswhenproperlydocumentedwillmakethecompletedprogrameasierforother programmerstomaintaininthefuture.Therearethreebroadareasofactivity: UnderstandingtheProgram UsingDesignToolstoCreateaModel DevelopTestData 2.1.2UnderstandingtheProgram Ifyouareworkingonaprojectasaoneofmanyprogrammers,thesystemanalystmayhavecreatedavariety ofdocumentationitemsthatwillhelpyouunderstandwhattheprogramistodo.Thesecouldincludescreen layouts,narrativedescriptions,documentationshowingtheprocessingsteps,etc.Ifyouarenotonaproject andyouarecreatingasimpleprogramyoumightbegivenonlyasimpledescriptionofthepurposeofthe program.Understandingthepurposeofaprogramusuallyinvolvesunderstandingit's: Inputs Processing Outputs This IPO approachworksverywellforbeginningprogrammers.Sometimes,itmighthelptovisualizethe programmingrunningonthecomputer.Youcanimaginewhatthemonitorwilllooklike,whattheuser mustenteronthekeyboardandwhatprocessingormanipulationswillbedone. 2.1.3UsingDesignToolstoCreateaModel Atrstyouwillnotneedahierarchychartbecauseyourrstprogramswillnotbecomplex.Butasthey growandbecomemorecomplex,youwilldivideyourprogramintoseveralmodulesorfunctions. Therstmodelingtoolyouwillusuallylearnis pseudocode .Youwilldocumentthelogicoralgorithm ofeachfunctioninyourprogram.Atrst,youwillhaveonlyonefunction,andthusyourpseudocodewill followcloselytheIPOapproachabove. 1 Thiscontentisavailableonlineat. 25

PAGE 34

26 CHAPTER2.2.PROGRAMPLANNING&DESIGN Thereareseveralmethodsortoolsforplanningthelogicofaprogram.Theyinclude:owcharting, hierarchyorstructurecharts,pseudocode,HIPO,Nassi-Schneidermancharts,Warnier-Orrdiagrams,etc. Programmersareexpectedtobeabletounderstandanddoowchartingandpseudocode.Thesemethodsof developingthemodelofaprogramareusuallytaughtinmostcomputercourses.Severalstandardsexistfor owchartingandpseudocodeandmostareverysimilartoeachother.However,mostcompanieshavetheir owndocumentationstandardsandstyles.Programmersareexpectedtobeabletoquicklyadapttoany owchartingorpseudocodestandardsforthecompanyatwhichtheywork.Theothersmethodsthatare lessuniversalrequiresometrainingwhichisgenerallyprovidedbytheemployerthatchoosestousethem. Laterinyourprogrammingcareer,youwilllearnaboutusingapplicationssoftwarethathelpscreatean informationsystemand/orprograms.ThistypeofsoftwareiscalledComputer-aidedSoftwareEngineering. Understandingthelogicandplanningthealgorithmonpaperbeforeyoustarttocodeisveryimportant concept.Manystudentsdeveloppoorhabitsandskippingthisstepisoneofthem. 2.1.4DevelopTestData Testdata consistsoftheuserprovidingsomeinputvaluesandpredictingtheoutputs.Thiscanbequite easyforasimpleprogramandthetestdatacanbeusedtocheckthemodeltoseeifitproducesthecorrect results. 2.1.5Denitions Denition2.1:IPO Inputs-Processing-Outputs Denition2.2:pseudocode English-likestatementsusedtoconveythestepsofanalgorithmorfunction. Denition2.3:testdata Providinginputvaluesandpredictingtheoutputs. 2.2Pseudocode 2 2.2.1Overview Pseudocodeisonemethodofdesigningorplanningaprogram. Pseudo meansfalse,thuspseudocodemeans falsecode.Abettertranslationwouldbethewordfakeorimitation.Pseudocodeisfakenottherealthing. ItlookslikeimitatesrealcodebutitisNOTrealcode.ItusesEnglishstatementstodescribewhata programistoaccomplish.Itisfakebecausenocomplierexiststhatwilltranslatethepseudocodetoany machinelanguage.Pseudocodeisusedfordocumentingtheprogramormoduledesignalsoknownasthe algorithm. Thefollowingoutlineofasimpleprogramillustratespseudocode.Wewanttobeabletoentertheages oftwopeopleandhavethecomputercalculatetheiraverageageanddisplaytheanswer. Example2.1:OutlineusingPseudocode Input displayamessageaskingtheusertoenterthefirstage getthefirstagefromthekeyboard displayamessageaskingtheusertoenterthesecondage getthesecondagefromthekeyboard 2 Thiscontentisavailableonlineat.

PAGE 35

27 Processing calculatetheanswerbyaddingthetwoagestogetheranddividingbytwo Output displaytheansweronthescreen pausesotheusercanseetheanswer Afterdevelopingtheprogramdesign,weusethepseudocodetowritecodeinalanguagelikePascal,COBOL, FORTRAN,"C","C++",etc.whereyoumustfollowtherulesofthelanguagesyntaxinordertocodethe logicoralgorithmpresentedinthepseudocode.Pseudocodeusuallydoesnotincludeotheritemsproduced duringprogrammingdesignsuchasidentierlistsforvariablesortestdata. Thereareothermethodsforplanninganddocumentingthelogicforaprogram.Onemethodis HIPO .It standsforHierarchyplusInputProcessOutputandwasdevelopedbyIBMinthe1960s.Itinvolvedusinga hierarchyorstructurecharttoshowtherelationshipofthesub-routinesorfunctionsinaprogram.Each sub-routinehadan IPO piece.Sincetheaboveproblem/taskwassimple,wedidnotneedtousemultiple sub-routines,thuswedidnotproduceahierarchychart.WedidincorporatetheIPOpartoftheconcept forthepseudocodeoutline. 2.2.2Denitions Denition2.4:pseudo Meansfalseandincludestheconceptsoffakeorimitation. 2.3TestData 3 2.3.1Overview Testdataconsistsoftheuserprovidingsomeinputvaluesandpredictingtheoutputs.Thiscanbequite easyforasimpleprogramandthetestdatacanbeusedtwice. 1.tocheckthemodeltoseeifitproducesthecorrectresults modelchecking 2.tocheckthecodedprogramtoseeifitproducesthecorrectresults codechecking Testdataisdevelopedbyusingthealgorithmoftheprogram.Thisalgorithmisusuallydocumentedduring theprogramdesignwitheitherowchartingorpseudocode.Hereisthepseudocodeinoutlineformdescribing theinputs,processingandoutputsforaprogramusedforpaintingrectangularbuildings. Example2.2:PseudocodeusinganIPOOutlineforPaintingaRectangularBuilding Input displayamessageaskinguserforthelengthofthebuilding getthelengthfromthekeyboard displayamessageaskinguserforthewidthofthebuilding getthewidthfromthekeyboard displayamessageaskinguserfortheheightofthebuilding gettheheightfromthekeyboard displayamessageaskinguserforthepricepergallonofpaint getthepricepergallonofpaintfromthekeyboard displayamessageaskinguserforthesqftcoverageofagallonofpaint getthesqftcoverageofagallonofpaintfromthekeyboard 3 Thiscontentisavailableonlineat.

PAGE 36

28 CHAPTER2.2.PROGRAMPLANNING&DESIGN Processing calculatethetotalareaofthebuildingby: multiplyingthelengthbyheightby2 thenmultiplythewidthbyheightby2 thenaddthetworesultstogether calculatethenumberofgallonsofpaintneededby: dividingthetotalareabythecoveragepergallon thenrounduptothenextwholegallon calculatethetotalcostofthepaintby: multiplyingthetotalgallonsneededbythepriceofonegallonofpaint Output displaythenumberofgallonsneededonthemonitor displaythetotalcostofthepaintonthemonitor pausesotheusercanseetheanswer 2.3.2CreatingTestDataandModelChecking Testdataisusedtoverifythattheinputs,processingandoutputsareworkingcorrectly.Astestdatais initiallydevelopeditcanverifythatthedocumentedalgorithmpseudocodeintheexamplewearedoing iscorrect.Ithelpsusunderstandandevenvisualizetheinputs,processingandoutputsoftheprogram. Inputs:Mybuildingis100feetlongby40feetwideand10feetinheightandIselectedpaintcosting$28.49 pergallonthatwillcover250squarefeetpergallon.Weshouldverifythatthepseudocodeispromptingthe userforthisdata. Processing:Usingmysolarpoweredhandheldcalculator,Icancalculateorpredictthetotalarea wouldbe:x10x2plus40x10x2or2,800sqft.Thetotalgallonsofpaintwouldbe:/250 or11.2gallons.Butroundedup,Iwouldneedtwelvegallonsofpaint.Thetotalcostwouldbe:.49 times12or$341.88.Weshouldverifythatthepseudocodeisperformingthecorrectcalculations. Output:Onlythesignicantinformationnumberofgallonstobuyandthetotalcostaredisplayedfor theusertosee.Weshouldverifythattheappropriateinformationisbeingdisplayed. 2.3.3TestingtheCodedProgramCodeChecking Thetestdatacanbedevelopedandusedtotestthealgorithmthatisdocumentedinourcaseourpseudocodeduringtheprogramdesignphase.Oncetheprogramiscodewithcompilerandlinkererrorsresolved, theprogrammergetstoplayuserandshouldtesttheprogramusingthetestdatadeveloped.Whenyou runyourprogram,howwillyouknowthatitisworkingproperly?Didyouproperlyplanyourlogicto accomplishyourpurpose?Evenifyourplanwascorrect,diditgetconvertedcorrectlycodedintothe chosenprogramminglanguageinourcaseC++?Theanswerorsolutiontoallofthesequestionsisour testdata. Bydevelopingtestdatawearepredictingwhattheresultsshouldbe,thuswecanverifythatour programisworkingproperly.Whenweruntheprogramwewouldentertheinputvaluesusedinourtest data.Hopefullytheprogramwilloutputthepredictedvalues.Ifnotthenourproblemcouldbeanyofthe following: 1.TheplanIPOoutlineorotheritemcouldbewrong 2.Theconversionoftheplantocodemightbewrong 3.Thetestdataresultswerecalculatedwrong Resolvingproblemsofthisnaturecanbethemostdicultproblemsaprogrammerencounters.Youmust revieweachoftheabovetodeterminewheretheerrorislies.Fixtheerrorandre-testyourprogram.

PAGE 37

29 2.3.4Denitions Denition2.5:modelchecking Usingtestdatatocheckthedesignmodelusuallydoneinpseudocode. Denition2.6:codechecking UsingtestdatatocheckthecodedprograminaspeciclanguagelikeC++. 2.4Practice2:ProgramPlanning&Design 4 2.4.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Createapseudocodedocumentforaprogrammingproblem 3.Createatestdatadocumentforaprogrammingproblem 2.4.2MemoryBuildingActivities Linkto:MBA02 5 2.4.3Exercises Exercise2.1 Solutiononp.32. Answerthefollowingstatementsaseithertrueorfalse: 1.CodingtheprograminalanguagelikeC++isthersttaskofplanning.Youplanasyou code. 2.Pseudocodeistheonlycommonlyusedplanningtool. 3.TestdataisdevelopedfortestingtheprogramonceitiscodeintoalanguagelikeC++. 4.Thewordpseudomeansfalseandincludestheconceptsoffakeorimitation. 5.Manyprogrammerspickupthebadhabitofnotcompletingtheplanningstepbeforestarting tocodetheprogram. 2.4.4MiscellaneousItems Noneatthistime. 2.4.5LabAssignment 2.4.5.1CreatingaFolderorSub-FolderforChapter02Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_02withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 4 Thiscontentisavailableonlineat. 5 Seetheleat

PAGE 38

30 CHAPTER2.2.PROGRAMPLANNING&DESIGN 2.4.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Solution_Lab_01_Pseudocode.txt 6 DownloadfromConnexions:Solution_Lab_01_Test_Data.txt 7 2.4.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. Navigatetoyoursub-folder:Chapter_02andprintthe:Solution_Lab_01_Pseudocode.txtandthe: Solution_Lab_01_Test_Data.txtles.ReviewtheprintoutsinconjunctionwithyourLab01source codele.Note:InLab01wegaveyoustepbystepdirectionsformodifyingtheCompiler_Test.cpp sourcecodeleintotheLab_01.cppsourcecodele.Icouldhavegivenyouthepseudocodeand testdatales,butyouhadnotreceivedanyinstructionsaboutthem.Now,afterhavingstudiedthe Chapter2materials,theselesshouldmakesense. Makecopiesofthe:Solution_Lab_01_Pseudocode.txtandSolution_Lab_01_Test_Data.txtand renamethem: Lab_02_Pseudocode.txt and Lab_02_Test_Data.txt Hereistheproblem.Yourlocalbankhasmanycustomerswhosavetheirchangeandperiodicallybring itinfordeposit.Thecustomershavesortedthecoinspennies,nickels,dimesandquartersforget halfdollarsanddollarcoinsandknowhowmanyanintegerdatatypeofeachvaluetheyhavebut haveevolvedortheirenvironmenthasmadethemlazy.Theyhavelosttheirabilitytodosimple arithmetic.Theycan'tseemtodeterminethetotalvalueofallofthecoinswithoutacalculatoror computer.Writeaprogramtointeractwiththecustomersandtodetermineandreportthetotal valueoftheircoins. No!No!No!Weare not goingtowriteaprogramcreatesourcecodeusingtheC++programming language.Wearegoingtodesignaplanforaprogramusingpseudocodeasourmodel.Additionally, weneedtodevelopsometestdataforuseintestingourmodel. StartyourtexteditorMicrosoftNotepad.SetthefontonNotepadto:Courier12fontbecauseCourier usesthesameamountofspacehorizontallyforeachletter.Itwillmaketheinformationintheles showasitshouldbeseen.OpenyourLab02pseudocodetextle.Changeallitemsasneededto beabletosolvetheaboveproblem.NOTE:Youmayuseanyapplicationsoftwarethatwillletyou open,modifyandsaveASCIItextles.YoumayevenusetheBloodshedDev-C++5compiler/IDE softwaretoview,modifyandsaveASCIItextles;afterall,oursourcecodelesareASCIItextles withaspecialextensionof.cpp OpenyourLab02testdatatextle.Modifythetextleasappropriate.Useyourtestdataandstep throughyourpseudocode.Doeseverythingseemtowork?Haveyoumissedsomething? Whenyouaresatisedthatyouhaveyourprogramplanandtestdatacompleted,closeyourtextles. That'sright,Isaid,"Saveandcloseyourtextles."Filesshouldbeproperlyclosedbeforebeingused byothersoftwareandthisincludestheOperatingSystemsoftwarethatmoves,copiesandrenames les. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 2.4.6Problems 2.4.6.1Problem02aInstructions CreatesimpleIPOpseudocodetosolvethefollowing: 6 Seetheleat 7 Seetheleat

PAGE 39

31 Problem:IhaveafriendwhoisvisitingfromEuropeandhedoesnotunderstandexactlyhowmuchgas heisbuyingforhiscar.Weneedtowriteaprogramthatallowshimtoenterthegallonsofgasandconvert ittolitersmetricsystem.NOTE:OneUSgallonequals3.7854liters. 2.4.6.2Problem02bInstructions Createtestdataforthefollowing: Problem:Amajorrestaurantsendsacheftopurchasefruitsandvegetableseveryday.Uponreturning tothestorethechefmustentertwopiecesofdataforeachitemhepurchased.ThequantityExample:2 casesandthepricehepaidExample:$4.67.Theprogramhasalistof20itemsandafterthechefenters theinformation,theprogramprovidesatotalforthepurchasesforthatday.Youneedtopreparetestdata forveitems:apples,oranges,bananas,lettuceandtomatoes.

PAGE 40

32 CHAPTER2.2.PROGRAMPLANNING&DESIGN SolutionstoExercisesinChapter2 SolutiontoExercise2.1p.29 Answers: 1.false 2.false 3.false 4.true 5.true

PAGE 41

Chapter3 3.Data&Operators 3.1DataTypesinC++ 1 3.1.1GeneralDiscussion Ourinteractionsinputsandoutputsofaprogramaretreatedinmanylanguagesasastreamofbytes. Thesebytesrepresentdatathatcanbeinterpretedasrepresentingvaluesthatweunderstand.Additionally, withinaprogramweprocessthisdatainvariouswayssuchasaddingthemuporsortingthem.Thisdata comesindierentforms.Examplesinclude:yournamewhichisastringofcharacters;youragewhichis usuallyaninteger;ortheamountofmoneyinyourpocketwhichisusuallyavaluemeasuredindollarsand centssomethingwithafractionalpart.Amajorpartofunderstandinghowtodesignandcodeprogramsin centeredinunderstandingthetypesofdatathatwewanttomanipulateandhowtomanipulatethatdata. "A type denesasetofvaluesandasetofoperationsthatcanbeappliedonthosevalues.Thesetof valuesforeachtypeisknownasthedomainforthattype." 2 Thefourmajorfamiliesofdatainclude: Nothing Integer Floating-point Complex TheC++programminglanguageidentiesvedatatypesasstandarddatatypes: Void Boolean Character Integer Floating-point ThestandarddatatypesandthecomplexdatatypeswithinC++haveaseriesofattributes,whichinclude: C++ReservedorKeyWord Domaintheallowedvalues Signagedotheyallownegativenumbersoronlypositivenumbers Meaningi.e.Whatdotheyrepresent RulesofDenitionWhatspecialcharactersindicatethedatatype Sizeintermsofthenumberofbytesofstorageusedinthememory 1 Thiscontentisavailableonlineat. 2 BehrouzA.ForouzanandRichardF.Gilberg, Computer Science A Structured Approach using C++ Second EditionUnited StatesofAmerica:ThompsonBrooks/Cole,200433. 33

PAGE 42

34 CHAPTER3.3.DATA&OPERATORS OperationsAllowedi.e.WhichoperatorscanIuseonthedatatype Placingsomeoftheaboveintoasummarytable,weget: Family DataType ReservedWord Represents StandardType Nothing Nullornothing void Nodata Yes Integer Boolean bool Logicaltrueand false Yes Integer Character char Singlecharacters Yes Integer Integer int Wholenumbers Yes FloatingPoint FloatingPoint oat Fractionalnumbers Yes Complex String string Asequencesting themalongof characters No Complex Array N/A Acollectionofelementsofthesame datatype No Complex Pointer N/A Avaluethat pointstoalocationanaddress withinthedata area No Table3.1 Thevestandarddatatypesusuallyexistinmostprogramminglanguagesandactorbehavesimilarly fromlanguagetolanguage.Mostcoursesofstudyforaprogrammingcourseorlanguagewillexplainthe standarddatatypesrst.Aftertheyarelearned,thecomplexdatatypesareintroduced. TheBoolean,characterandintegerdatatypesareidentiedasbelongingtotheIntegerFamily.These datatypesareallrepresentedbyintegernumbersandthusactorbehavesimilarly. 3.1.2Denitions Denition3.1:datatype Denesasetofvaluesandasetofoperationsthatcanbeappliedonthosevalues. Denition3.2:datetypefamilies 1Nothing2Integer3Floating-Point4Complex Denition3.3:domain Thesetofallowedvaluesforadatatype. Denition3.4:integer Adatatyperepresentingwholenumbers. Denition3.5:oatingpoint Adatatyperepresentingnumberswithfractionalparts.

PAGE 43

35 3.2IdentierNames 3 3.2.1Overview Withinprogrammingavarietyofitemsaregivendescriptivenamestomakethecodemoremeaningfulto usashumans.Thesenamesarecalled"IdentierNames".Constants,variables,typedenitions,functions, etc.whendeclaredordenedareidentiedbyaname.Thesenamesfollowasetofrulesthatareimposed by: 1.thelanguage'stechnicallimitations 2.goodprogrammingpractices 3.commonindustrystandardsforthelanguage 3.2.2TechnicaltoLanguage UseonlyallowablecharactersforC++therstcharacteralphabeticorunderscore,cancontinuewith alphanumericorunderscore Can'tusereservedwords Lengthlimit Theseattributesvaryfromoneprogramminglanguagetoanother.Theallowablecharactersandreserved wordswillbedierent.Thelengthlimitreferstohowmanycharactersareallowedinanidentiername andofteniscompilerdependentandmayvaryfromcompilertocompilerforthesamelanguage.However, allprogramminglanguageshavethesethreetechnicalrules. 3.2.3GoodProgrammingTechniques Meaningful Becaseconsistent Meaningfulidentiernamesmakeyourcodeeasierforanothertounderstand.Afterallwhatdoes"p"mean? Isitpi,price,pennies,etc.Thusdonotusecrypticlookitupinthedictionaryidentiernames. Someprogramminglanguagestreatupperandlowercaselettersusedinidentiernamesasthesame. Thus:pigandPigaretreatedasthesameidentiername.Unknowntoyoutheprogrammer,thecompiler usuallyforcesallidentiernamestouppercase.Thus:pigandPigbothgetchangedtoPIG.However notallprogramminglanguagesactthisway.Somewilltreatupperandlowercaselettersasbeingdierent things.Thus:pigandPigaretwodierentidentiernames.Ifyoudeclareitaspigandthenreferenceitin yourcodelaterasPigyougetacompilererror.Toavoidtheproblemaltogether,weteachstudentsto be caseconsistent .Useanidentiernameonlyonceandspellitupperandlowercasethesamewaywithin yourprogram. 3.2.4IndustryRules Donotstartwithunderscoreusedfortechnicalprogramming variablesinalllowercase CONSTANTSINALLUPPERCASE Theserulesaredecidedbytheindustrythosewhoareusingtheprogramminglanguage.Theaboverules werecommonlyusedwithinthe"C"programminglanguageandhavetolargedegreecarriedovertoC++. 3 Thiscontentisavailableonlineat.

PAGE 44

36 CHAPTER3.3.DATA&OPERATORS 3.2.5Denitions Denition3.6:reservedword Wordsthatcannotbeusedbytheprogrammerasidentiernamesbecausetheyalreadyhavea specicmeaningwithintheprogramminglanguage. 3.3ConstantsandVariables 4 3.3.1UnderstandingConstants Varioustextbooksdescribeconstantsusingdierentterminology.Addedtothecomplexityaretheexplanationsfromvariousindustryprofessionalswillvarygreatly.Let'sseeifwecanclearitup. A constant isadataitemwhosevaluecannotchangeduringtheprogram'sexecution.Thus,asitsname impliestheirvalueisconstant. A variable isadataitemwhosevaluecanchangeduringtheprogram'sexecution.Thus,asitsname impliestheirvaluecanvary. ConstantsareusedinthreewayswithinC++.Theyare: 1.literalconstant 2.denedconstant 3.memoryconstant A literalconstant isa value youtypeintoyourprogramwhereveritisneeded.Examplesincludethe constantsusedforinitializingavariableandconstantsusedinlinesofcode: Example3.1:LiteralConstants intage=21; chargrade='A'; floatmoney=12.34; boolrich=false; cout n nStudentslovecomputers"; age=57; Additionally,wehavelearnedhowtorecognizethedatatypesofliteralconstants.Singlequotesforchar, doublequotesforstring,numberwithoutadecimalpointforinteger,numberwithadecimalpointbelongs totheoating-pointfamily,andBooleancanusethereservedwordsoftrueorfalse. Inadditiontoliteralconstants,mosttextbooksrefertoeithersymbolicconstantsornamedconstants butthesetworefertothesameconcept.Asymbolicconstantisrepresentedbyanamesimilartohowwe namevariables.Let'ssayitbackwards;theidentiernameisthesymbolthatrepresentsthedataitem. WithinC++identiernameshavesomerules.Oneoftherulessaysthosenamesshouldbemeaningful. AnotherruleaboutusingALLCAPSFORCONSTANTSisanindustryrule.Therearetwowaystocreate symbolicornamedconstants: #definePI3.14159 Calleda denedconstant becauseitusesatextualsubstitutionmethodcontrolledbythecompiler pre-processorcommandword"dene". constdoublePI=3.14159; 4 Thiscontentisavailableonlineat.

PAGE 45

37 Thesecondoneiscalledsometimescalled constantvariable butthatnameiscontradictoryallby itself.Howcanitbeconstantandvaryatthesametime?Thebetternameforthesecondoneisa memory constant becausetheyhavea"specicstoragelocationinmemory". 3.3.2DeningConstantsandVariables Intheaboveexamplesweseehowtodenebothvariablesandconstantsalongwithgivingthemaninitial value.Memoryconstantsmustbeassignedavaluewhentheyaredened.Butvariablesdonothavetobe assignedinitialvalues. intheight; floatvalue_coins; Variablesoncedenedmaybeassignedavaluewithintheinstructionsoftheprogram. height=72; value_coins=2*0.25+3*0.05; 3.3.3Denitions Denition3.7:constant Adataitemwhosevaluecannotchangeduringtheprogram'sexecution. Denition3.8:variable Adataitemwhosevaluecanchangeduringtheprogram'sexecution. 3.4DataManipulation 5 3.4.1Introduction Singlevaluesbythemselvesareimportant;howeverweneedamethodofmanipulatingvaluesprocessing data.Scientistswantedanaccuratemachineformanipulatingvalues.Theywantedamachinetoprocess numbersorcalculateanswersthatiscomputetheanswer.Priorto1950,dictionarieslistedthedenitionof computersas"humansthatdocomputations".Thus,alloftheterminologyfordescribingdatamanipulation ismathoriented.Additionally,thetwofundamentaldatatypefamiliestheintegerfamilyandoating-point familyconsistentirelyofnumbervalues. 3.4.2Denitions Denition3.9:expression Avalidsequenceofoperandsandoperatorsthatreducesorevaluatestoasinglevalue. Denition3.10:operator Alanguage-specicsyntacticaltokenusuallyasymbolthatcausesanactiontobetakenonone ormoreoperands. Denition3.11:operand Avaluethatreceivestheoperator'saction. Denition3.12:precedence Determinestheorderinwhichtheoperatorsareallowedtomanipulatetheoperands. Denition3.13:associativity Determinestheorderinwhichtheoperatorsofthesameprecedenceareallowedtomanipulatethe operands. 5 Thiscontentisavailableonlineat.

PAGE 46

38 CHAPTER3.3.DATA&OPERATORS Denition3.14:evaluation Theprocessofapplyingtheoperatorstotheoperandsandresultinginasinglevalue. Denition3.15:parentheses Changetheorderofevaluationinanexpression.Youdowhat'sintheparenthesesrst. 3.4.3AnExpressionExamplewithEvaluation Let'slookatanexample:2+3*4+5isourexpressionbutwhatdoesitequal? 1.thesymbolsof+meaningadditionand*meaningmultiplicationareouroperators 2.thevalues2,3,4and5areouroperands 3.precedencesaysthatmultiplicationishigherthanaddition 4.thus,weevaluatethe3*4toget12 5.nowwehave:2+12+5 6.theassociativityrulessaythatadditiongoeslefttoright,thusweevaluatethe2+12toget14 7.nowwehave:14+5 8.nally,weevaluatethe14+5toget19;whichisthevalueoftheexpression Parentheseswouldchangetheoutcome.+3*+5evaluatesto45. Parentheseswouldchangetheoutcome.+3*4+5evaluatesto25. 3.4.4PrecedenceofOperatorsChart Eachcomputerlanguagehassomerulesthatdeneprecedenceandassociativity.Theyoftenfollowrules wemayhavealreadylearned.Multiplicationanddivisioncomebeforeadditionandsubtractionisarulewe learnedingradeschool.Thisrulestillworks.Theprecedencerulesvaryfromoneprogramminglanguage toanother.Youshouldrefertothereferencesheetthatsummarizestherulesforthelanguagethatyouare using.ItisoftencalledaPrecedenceofOperatorsChart.Youshouldreviewthischartasneededwhen evaluatingexpressions. Avalidexpressionconsistsofoperandsandoperatorsthatareputtogetherproperly.Whythes? Someoperatorsare: 1.Unarythatisonlyhaveoneoperand 2.Binarythatishavetwooperands,oneoneachsideoftheoperator 3.Trinarywhichhastwooperatorsymbolsthatseparatethreeoperands Mostoperatorsarebinary,thatistheyrequiretwooperands.WithinC++thereisonlyonetrinaryoperator, theconditional.Alloftheunaryoperatorsareontheleftsideoftheoperand,exceptpostxincrementand postxdecrement.Someprecedencechartsindicateofwhichoperatorsareunaryandtrinaryandthusall othersarebinary. 3.5AssignmentOperator 6 3.5.1Discussion Theassignmentoperatorallowsustochangethevalueofamodiabledataobjectforbeginningprogrammers thistypicallymeansavariable.Itisassociatedwiththeconceptofmovingavalueintothestoragelocation againusuallyavariable.WithinC++programminglanguagethesymbolusedistheequalsymbol.But biteyourtongue,whenyouseethe=symbolyouneedtostartthinking:assignment.Theassignment operatorhastwooperands.Theonetotheleftoftheoperatorisusuallyanidentiernameforavariable. Theonetotherightoftheoperatorisavalue. 6 Thiscontentisavailableonlineat.

PAGE 47

39 Example3.2:SimpleAssignment intage;//variablesetup thenlaterintheprogram age=21; Thevalue21ismovedtothememorylocationforthevariablenamed:age.Anotherwaytosayit:ageis assignedthevalue21. Example3.3:AssignmentwithanExpression inttotal_cousins;//variablesetup thenlaterintheprogram cousins=4+3+5+2; Theitemtotherightoftheassignmentoperatorisanexpression.Theexpressionwillbeevaluatedandthe answeris14.Thevalue14wouldassignedtothevariablenamed:total_cousins. Example3.4:AssignmentwithIdentierNamesintheExpression intstudents_period_1=25;//variablesetupwithinitialization intstudents_period_2=19; inttotal_students; thenlaterintheprogram total_students=students_period_1+students_period_2; Theexpressiontotherightoftheassignmentoperatorcontainssomeidentiernames.Theprogramwould fetchthevaluesstoredinthosevariables;addthemtogetherandgetavalueof44;thenassignthe44tothe total_studentsvariable. 3.5.2Denitions Denition3.16:assignment Anoperatorthatchangesthevalueofamodiabledataobject. 3.6ArithmeticOperators 7 3.6.1GeneralDiscussion Anoperatorperformsanactionononeormoreoperands.Thecommonarithmeticoperatorsare: 7 Thiscontentisavailableonlineat.

PAGE 48

40 CHAPTER3.3.DATA&OPERATORS Action C++operatorsymbol Addition + Subtraction Multiplication Division / Modulusassociatedwithintegers % Table3.2 Thesearithmeticoperatorsarebinarythatistheyhavetwooperands.Theoperandsmaybeeither constantsorvariables. age+1 Thisexpressionconsistsofoneoperatoradditionwhichhastwooperands.Therstisrepresentedby avariablenamedageandthesecondisaliteralconstant.Ifagehadavalueof14thentheexpressionwould evaluateorbeequalto15. Theseoperatorsworkasyouhavelearnedthemthroughoutyourlifewiththeexceptionofdivisionand modulus.Wenormallythinkofdivisionasresultinginananswerthatmighthaveafractionalparta oating-pointdatatype.However,divisionwhenbothoperandsareoftheintegerdatatypeactdierently. Pleaserefertothesupplementalmaterialson"IntegerDivisionandModulus". 3.7DataTypeConversions 8 3.7.1Overview Changingadatatypeofavalueisreferredtoas"typeconversion".Therearetwowaystodothis: 1. Implicit thechangeisimplied 2. Explicit thechangeisexplicitlydonewiththecastoperator Thevaluebeingchangedmaybe: 1. Promotion goingfromasmallerdomaintoalargerdomain 2. Demotion goingfromalargerdomaintoasmallerdomain 3.7.2ImplicitTypeConversion Automaticconversionofavaluefromonedatatypetoanotherbyaprogramminglanguage,withoutthe programmerspecicallydoingso,iscalledimplicittypeconversion.Ithappenswheneverabinaryoperator hastwooperandsofdierentdatatypes.Dependingontheoperator,oneoftheoperandsisgoingtobe convertedtothedatatypeoftheother.Itcouldbepromotedordemoteddependingontheoperator. Example3.5:ImplicitPromotion 55+1.75 8 Thiscontentisavailableonlineat.

PAGE 49

41 Inthisexampletheintegervalue55isconvertedtoaoating-pointvaluemostlikelydoubleof55.0.It waspromoted. Example3.6:ImplicitDemotion intmoney;//variablesetup thenlaterintheprogram money=23.16; Inthisexamplethevariablemoneyisaninteger.Wearetryingtomoveaoating-pointvalue23.16intoan integerstoragelocation.Thisisdemotionandtheoating-pointvalueusuallygetstruncatedto23. 3.7.3Promotion Promotionisneveraproblembecausethelowerdatatypesmallerrangeofallowablevaluesissubsetof thehigherdatatypelargerrangeofallowablevalues.Promotionoftenoccurswiththreeofthestandard datatypes:character,integerandoating-point.Theallowablevaluesordomainsprogressfromonetype toanother.Thatisthecharacterdatatypevaluesareasubsetofintegervaluesandintegervaluesareasub setofoating-pointvalues;andwithintheoating-pointvalues:oatvaluesareasubsetofdouble.Even thoughcharacterdatarepresentthealphabeticletters,numeraldigitsto9andothersymbolsaperiod, $,comma,etc.theirbitpatternalsorepresentintegervaluesfrom0to255.Thisprogressionallowsusto promotethemupthechainfromcharactertointegertooattodouble. 3.7.4Demotion Demotionrepresentsapotentialproblemwithtruncationorunpredictableresultsoftenoccurring.Howdo youtanintegervalueof456intoacharactervalue?Howdoyouttheoating-pointvalueof45656.453 intoanintegervalue?Mostcompilersgiveawarningifitdetectsdemotionhappening.Acompilerwarning doesnotstopthecompilationprocess.Itdoeswarntheprogrammertochecktoseeifthedemotionis reasonable. IfIcalculatethenumberofcansofsouptobuybasedonthenumberofpeopleIamservingsay8and theservingspercansay2.3,Iwouldneed18.4cans.Imightwanttodemotethe18.4intoaninteger.It wouldtruncatethe18.4into18andbecausethevalue18iswithinthedomainofanintegerdatatype,it shoulddemotewiththe truncation sideeect. IfItrieddemotingadoublethatcontainedthenumberofstarsintheMilkyWaygalaxyintoaninteger, Imighthaveagetan unpredictableresult assumingthenumberofstarsislargerthanallowablevalues withintheintegerdomain. 3.7.5ExplicitTypeConversion Mostlanguageshaveamethodfortheprogrammertochangeorcastavaluefromonedatatypetoanother; called explicittypeconversion .WithinC++thecastoperatorisaunaryoperator;itonlyhasone operandandtheoperandistotherightoftheoperator.Theoperatorisasetofparenthesessurrounding thenewdatatype. Example3.7:ExplicitDemotionwithTruncation int4.234 Thisexpressionwouldevaluateto:4.

PAGE 50

42 CHAPTER3.3.DATA&OPERATORS 3.7.6DemonstrationPrograminC++ 3.7.6.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 3.7.6.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesorucecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Data_Type_Conversions.cpp 9 3.7.7Denitions Denition3.17:implicit Avaluethathasitsdatatypechangedautomatically. Denition3.18:explicit Changingavalue'sdatatypewiththecastoperator. Denition3.19:promotion Goingfromasmallerdomaintoalargerdomain. Denition3.20:demotion Goingfromalargerdomaintoasmallerdomain. Denition3.21:truncation Thefractionalpartofaoating-pointdatatypethatisdroppedwhenconvertedtoaninteger. 3.8Practice3:Data&Operators 10 3.8.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Understandbasicdatatypesandhowoperatorsmanipulatedata. 3.Givenpseudocodeandtestdatadocuments,writetheC++codeforaprogram 3.8.2MemoryBuildingActivities Linkto:MBA03 11 9 Seetheleat 10 Thiscontentisavailableonlineat. 11 Seetheleat

PAGE 51

43 3.8.3Exercises Exercise3.1 Solutiononp.45. Answerthefollowingstatementsaseithertrueorfalse: 1.Adatatypedenesasetofvaluesandthesetofoperationsthatcanbeappliedonthose values. 2.Reservedorkeywordscanbeusedasidentiernames. 3.Theconceptofprecedencesaysthatsomeoperatorslikemultiplicationanddivisionareto beexecutedbeforeotheroperatorslikeadditionandsubtraction. 4.Anoperatorthatneedstwooperands,willpromoteoneoftheoperandsasneededtomake bothoperandsbeofthesamedatatype. 5.Parentheseschangetheprecedenceofoperators. 3.8.4MiscellaneousItems Linkto:ManipulationofDataPart1 12 3.8.5LabAssignment 3.8.5.1CreatingaFolderorSub-FolderforChapter03Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_03withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 3.8.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Solution_Lab_03_Pseudocode.txt 13 DownloadfromConnexions:Solution_Lab_03_Test_Data.txt 14 3.8.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. Navigatetoyoursub-folder:Chapter_03andopenandstudythetwoles. Wehavelearnedthatafundamentalconceptofinteractionwithcomputersistodividetheproblem/task intothreepartsinput,processingandoutput.ThisproblemissimpleandwewillusetheIPO inputprocessingoutputapproachagain. Howeverthistimewearegoingtothinkabout itbackwards. WhatoutputdoIwantdisplayed? 12 Seetheleat 13 Seetheleat 14 Seetheleat

PAGE 52

44 CHAPTER3.3.DATA&OPERATORS Numberofgallonsofpaint Totalcostofthepaint Thus,whatcalculationsdoIneedtomake? TotalcostofthepaintistheNumberofgallonsneededtimespricepergallon NumberofgallonsneededistheTotalareatobecoveredlet'susesquarefeetdividedbythecoverage pergallonofpaintNote:youmustrounduptothenextfullgallonofpaint. TotalareatobecoveredistheLengthtimesheighttimes2addedtothewidthtimesheighttimes2 Whichleadsusto,whatdatadoIneedasinput? Priceofagallonofpaint Numberofsquarefeetthatagallonwillcover Lengthofthehouse Widthofthehouse Heightofthehouse Youcanseethatbyworkingthelogicbackwards,wecanstarttocompletelyseewhattheprogram mustdo.Weneedtoentersomedatainput,dosomecalculationsprocessanddisplaytheresults output. Copyintoyoursub-folder:Chapter_03oneofthesourcecodelistingsthatwehaveusedwesuggest theLab01sourcecodeandrenamethecopyto: Lab_03.cpp ModifythecodetofollowtheSolution_Lab_03_Pseudocode.txtle. IamjustgoingtogiveyouthelineofcodeforroundinguptothenextwholegallonofpaintSeethe DataTypeConversionsmodulewithinChapter3oftheConnexionsmaterials.Doyouunderstand whyitworks?. total_gal_paint=total_area/coverage_gal_paint+0.9999; Buildcompileandrunyourprogram.Youhavesuccessfullywrittenthisprogramwhenitrunswith yourtestdataandgivesthepredictedresults. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 3.8.6Problems 3.8.6.1Problem03aInstructions WritetheC++codetodothefollowingpseudocodeexample. Example3.8:pseudocode Prompttheuserforhismonthlyincome. Gettheusersmonthlyincome. Multiplythemonthlyincomeby12. Displaytheannualincome. Pausetheprogramsotheusercanseetheanswer.HINT:Youmaycallafunction.

PAGE 53

45 SolutionstoExercisesinChapter3 SolutiontoExercise3.1p.43 Answers: 1.true 2.false 3.true 4.true 5.falseParentheseschangetheorderofevaluationinanexpression.

PAGE 54

46 CHAPTER3.3.DATA&OPERATORS

PAGE 55

Chapter4 4.OftenUsedDataTypes 4.1IntegerDataType 1 4.1.1GeneralDiscussion Theintegerdatatypehastwomeanings: Theintegerdatatypewithitsvariousmodiersthatcreatedierentdomains TheintegerfamilywhichalsoincludestheBooleanandcharacterdatatypes Theintegerdatatypebasicallyrepresentswholenumbersnofractionalparts.Theintegervaluesjump fromonevaluetoanother.Thereisnothingbetween6and7.Itcouldbeaskedwhynotmakeallyour numbersoatingpointwhichallowforfractionalparts.Thereasonistwofold.First,somethingsinthereal worldarenotfractional.Adog,evenwithonly3legs,isstillonedognot ofadog.Second,integer datatypeisoftenusedtocontrolprogramowbycounting,thustheneedforadatatypethatjumpsfrom onevaluetoanother. Theintegerdatatypehasthesameattributesandactsorbehavessimilarlyinallprogramminglanguages. ThemostoftenusedintegerdatatypeinC++isthesimpleinteger. C++ReservedWord int Represent Wholenumbersnofractionalparts Size Usually4bytes NormalSignage Signednegativeandpositivevalues DomainValuesAllowed -2,147,483,648to2,147,483,647 C++syntaxrule Donotstartwitha0zero C++syntaxrule Nodecimalpoint Table4.1 WithinC++therearevariousreservedwordsthatcanbeusedtomodifythesizeorsignageofaninteger. Theyinclude:long,short,signedandunsigned.Signedisrarelyusedbecauseintegersaresignedbydefault youmustspecifyunsignedifyouwantintegersthatareonlypositive.Possiblecombinationsare: 1 Thiscontentisavailableonlineat. 47

PAGE 56

48 CHAPTER4.4.OFTENUSEDDATATYPES C++ReservedWordCombination Signage shortint signed unsignedshortint unsigned int signed unsignedint unsigned longint singed unsignedlongint unsigned Table4.2 Thedomainofeachoftheabovedatatypeoptionsvarieswiththecomplierbeingusedandthecomputer. Thedomainsvarybecausethebytesizeallocatedtothedatavarieswiththecompilerandcomputer.This eectisknownasbeing machinedependent .Additionally,therehavebeensomesizechangeswith upgradestothelanguage.In"C"theintdatatypewasallocated2bytesofmemorystorageonanIntel compatiblecentralprocessingunitcpumachine.In"C++"anintisallocated4bytes. ThesevariationsoftheintegerdatatypeareanannoyanceinC++forabeginningprogrammer.Fora beginningprogrammeritismoreimportanttounderstandthegeneralattributesoftheintegerdatatype thatapplytomostprogramminglanguages. 4.1.2Denitions Denition4.1:machinedependent Anattributeofaprogramminglanguagethatchangesdependingonthecomputer'sCPU. 4.2Floating-PointDataType 2 4.2.1GeneralDiscussion Theoating-pointdatatypeisafamilyofdatatypesthatactalikeanddieronlyinthesizeoftheirdomains theallowablevalues.Theoating-pointfamilyofdatatypesrepresentnumbervalueswithfractionalparts. Theyaretechnicallystoredastwointegervalues:a mantissa andan exponent .Theoating-pointfamily hasthesameattributesandactsorbehavessimilarlyinallprogramminglanguages.Theycanalwaysstore negativeorpositivevaluesthustheyalwaysaresigned;unliketheintegerdatatypethatcouldbeunsigned. The domain foroating-pointdatatypesvariesbecausetheycouldrepresentverylargenumbersorvery smallnumbers.Ratherthantalkabouttheactualvalues,wementionthe precision .Themorebytesof storagethelargerthemantissaandexponent,thusmoreprecision. Themostoftenusedoating-pointfamilydatatypeusedinC++isthe double .Bydefault,most compilersconvertoating-pointconstantsintothedoubledatatypeforuseincalculations.Thedoubledata typewillstorejustaboutanynumbermostbeginningprogrammerswilleverencounter. 2 Thiscontentisavailableonlineat.

PAGE 57

49 C++ReservedWord double Represent Numberswithfractionalparts Size Usually8bytes Storage twopartsalwaystreatedtogetheramantissaandanexponent NormalSignage Signednegativeandpositivevalues DomainValuesAllowed 1.7E-308to 1.7E308 C++syntaxrule thepresenceofadecimalpointmeansit'soating-pointdata Table4.3 WithinC++therearevariousreservedwordsthatcanbeusedtoestablishthesizeinbytesofaoatingpointdataitem.Morebytesmeanmoreprecision: C++ReservedWord Size oat 4bytes double 8bytes longdouble 10to12bytesvariesbymachine Table4.4 Thedomainofeachoftheabovedatatypeoptionsvarieswiththecomplierbeingusedandthecomputer. Thedomainsvarybecausethebytesizeallocatedtothedatavarieswiththecompilerandcomputer.This eectisknownasbeing machinedependent Thesevariationsoftheoating-pointfamilyofdatatypesareanannoyanceinC++forabeginning programmer.Forabeginningprogrammeritismoreimportanttounderstandthegeneralattributesofthe oating-pointfamilythatapplytomostprogramminglanguages. 4.2.2Denitions Denition4.2:double Themostoftenusedoating-pointfamilydatatypeusedinC++. Denition4.3:precision Theeectonthedomainofoating-pointvaluesgivenalargerorsmallerstorageareainbytes. Denition4.4:mantissaexponent Thetwointegerpartsofaoating-pointvalue. 4.3StringDataType 3 4.3.1GeneralDiscussion Technically,thereisnostringdatatypeintheC++programminglanguage.However,theconceptofa stringdatatypemakesiteasytohandlestingsofcharacterdata.Asinglecharacterhassomelimitations. Manydataitemsarenotintegersoroating-pointvalues.Themessage HiMom! isagoodexampleofa string.Thus,theneedtohandleaseriesofcharactersasasinglepieceofdatainEnglishcorrectlycalleda datum. 3 Thiscontentisavailableonlineat.

PAGE 58

50 CHAPTER4.4.OFTENUSEDDATATYPES Inthe"C"programminglanguageallstringwerehandledasanarrayofcharactersthatendinanASCII nullcharacterthevalue0ortherstcharacterintheASCIIcharactercodeset.Associatedwithobject orientedprogrammingthestringclasshasbeenaddedtoC++asastandardpartoftheprogramming language.Thischangedwiththeimplementationwithstringsbeingstoredasalengthcontrolleditemwith amaximumlengthof255characters.IncludedintheC++stringclassisthereservedwordof string asif itwereadatatype.Somebasicsaboutstringsinclude: C++ReservedWord string Represent Seriesofcharacterstechnicallyanarray Size Variesinlength NormalSignage N/A DomainValuesAllowed ExtendedASCIICharacterCodeSet C++syntaxrule Doublequotemarksforconstants Table4.5 Fornow,wewilladdressonlytheuseofstringsasconstants.Mostmoderncompliersthatarepartofan IntegratedDevelopmentEnvironmentIDEwillcolorthesourcecodetohelptheprogrammerseedierent featuresmorereadily.Beginningprogrammerswillusestringconstantstosendmessagestothemonitor.A typicallineofC++code: cout "HiMom!"; wouldhavethe"HiMom"coloredusuallyredtoemphasizethattheitemisastring. 4.3.2Denitions Denition4.5:string Aseriesorarrayofcharactersasasinglepieceofdata. 4.4ArithmeticAssignmentOperators 4 4.4.1OverviewofArithmeticAssignment Theve arithmeticassignment operatorsareaformofshorthand.Varioustextbookscallthem"compoundassignmentoperators"or"combinedassignmentoperators".Theirusagecanbeexplanedinterms oftheassignmentoperatorandthearithmeticoperators.Inthetablewewillusethevariableageandyou canassumethatitisofintegerdatatype. Arithmeticassignmentexamples: Equivalentcode: age+=14; age=age+14; age-=14; age=age-14; continuedonnextpage 4 Thiscontentisavailableonlineat.

PAGE 59

51 age*=14; age=age*14; age/=14; age=age/14; age%=14; age=age%14; Table4.6 4.4.2DemonstrationPrograminC++ 4.4.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 4.4.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesorucecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Arithmetic_Assignment.cpp 5 4.5LvalueandRvalue 6 4.5.1Discussion Theyrefertoontheleftandrightsideoftheassignmentoperator.The Lvalue pronounced:Lvalue conceptreferstotherequirementthattheoperandontheleftsideoftheassignmentoperatorismodiable, usuallyavariable. Rvalue conceptpullsorfetchesthevalueoftheexpressionoroperandontherightside oftheassignmentoperator.Someexamples: Example4.1 intage;//variablesetup thenlaterintheprogram age=39; Thevalue39ispulledorfetchedRvalueandstoredintothevariablenamedageLvalue;destroyingthe valuepreviouslystoredinthatvariable. Example4.2 5 Seetheleat 6 Thiscontentisavailableonlineat.

PAGE 60

52 CHAPTER4.4.OFTENUSEDDATATYPES intage;//variablesetup intvoting_age=18;//variablesetupwithinitialization thenlaterintheprogram age=voting_age; Iftheexpressionhasavariableornamedconstantontherightsideoftheassignmentoperator,itwould pullorfetchthevaluestoredinthevariableorconstant.Thevalue18ispulledorfetchedfromthevariable namedvoting_ageandstoredintothevariablenamedage. Example4.3 age < 17; Iftheexpressionisa testexpression or Booleanexpression ,theconceptisstillanRvalueone.The valueintheidentiernamedageispulledorfetchedandusedintherelationalcomparisonoflessthan. Example4.4 constintJACK_BENNYS_AGE=39;//constantsetup thenlaterintheprogram JACK_BENNYS_AGE=65; ThisisillegalbecausetheidentierJACK_BENNYS_AGEdoesnothaveLvalueproperties.Itisnota modiabledataobject,becauseitisaconstant. SomeusesoftheLvalueandRvaluecanbeconfusing. Example4.5 intoldest=55;//variablesetupwithinitialization thenlaterintheprogram age=oldest++; Postxincrementsaystousemyexistingvaluethenwhenyouaredonewiththeotheroperators;increment me.Thus,therstuseoftheoldestvariableisanRvaluecontextwheretheexistingvalueof55ispulled orfetchedandthenassignedtothevariableage;anLvaluecontext.Theseconduseoftheoldestvariableis anLvaluecontextwhereinthevalueofoldestisincrementedfrom55to56. 4.5.2Denitions Denition4.6:Lvalue Therequirementthattheoperandontheleftsideoftheassignmentoperatorismodiable,usually avariable. Denition4.7:Rvalue Pullsorfetchesthevaluestoredinavariableorconstant.

PAGE 61

53 4.6IntegerDivisionandModulus 7 4.6.1OverviewofIntegerDivisionandModulus Bythetimewereachadulthood,wenormallythinkofdivisionasresultinginananswerthatmighthave afractionalpartaoating-pointdatatype.Thistypeofdivisionisknownas oating-pointdivision However,divisionwhenbothoperandsareoftheintegerdatatypeactsdierentlyonmostcomputersand iscalled: integerdivision .WithintheC++programminglanguagethefollowingexpressiondoesnotgive theanswerof2.75or2 Example4.6 11/4 Becausebothoperandsareoftheintegerdatatypetheevaluationoftheexpressionoranswerwouldbe2 withnofractionalpartitgetsthrownaway.Again,thistypeofdivisioniscall integerdivision anditis whatyoulearnedingradeschoolthersttimeyoulearnedaboutdivision. Denition4.8:integerdivision Divisionwithnofractionalparts. Figure4.1: Integerdivisionaslearnedingradeschool. Intherealworldofdatamanipulationtherearesomethingsthatarealwayshandledinwholeunitsor numbersintegerdatatype. Fractionsjustdon'texist. Toillustrateourexample:Ihave11dollar coinstodistributeequallytomy4children.Howmanydotheyeachget?Answeris2withmestillhaving 3leftoverorwith3stillremaininginmyhand.Theanswerisnot2 eachor2.75foreachchild.The dollarcoinsarenotdivisibleintofractionalpieces.Don'ttrythinkingoutoftheboxandpretendyou'rea pirate.Usinganaxeandchoppingthe3remainingcoinsintopiecesofeight.Then,givingeachchild2coins and6piecesofeightor26/8or2 or2.75.Ifyoudothinkthisway,Iwillchangemyexampletocansof tomatosoup.Idareyoutotryandchopupthreecansofsoupandgiveeachkid ofacan.Betteryet, 7 Thiscontentisavailableonlineat.

PAGE 62

54 CHAPTER4.4.OFTENUSEDDATATYPES livingthingslikepuppydogs.Afteryoudividethemupwithanaxe,mostchildrenwillnotwantthe ofa dog. Whatis modulus ?It'stheotherpartoftheanswerforintegerdivision.It'stheremainder.Remember ingradeschoolyouwouldsay,"Elevendividedbyfouristworemainderthree."InC++programming languagethesymbolforthemodulusoperatoristhepercentsign%. Example4.7 11%4 Thus,theanswerorvalueofthisexpressionis3ortheremainderpartofintegerdivision. Denition4.9:modulus Theremainderpartofintegerdivision. Manycompilersrequirethatyouhaveintegeroperandsonbothsidesofthemodulusoperatororyouwill getacompilererror.Inotherwords,itdoesnotmakesensetousethemodulusoperatorwithoating-point operands. Don'tletthefollowingitemsconfuseyou. Example4.8 6/24whichisdifferentfrom6%24 Howmanytimescanyoudivide24into6?Sixdiviedby24iszero.Thisisdierentfrom:Whatisthe remainderof6dividedby24?Six,theremainderpartgivenbymodulus. Exercise4.1 Solutiononp.57. Evaluatethefollowingdivisionexpressions: 1.14/4 2.5/13 3.7/2.0 Exercise4.2 Solutiononp.57. Evaluatethefollowingmodulusexpressions: 1.14%4 2.5%13 3.7%2.0 4.6.2DemonstrationPrograminC++ 4.6.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate.

PAGE 63

55 4.6.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele.Followingthemethods ofyourcompiler/IDE,compileandruntheprograms.Studythesorucecodelesinconjunctionwith otherlearningmaterials. DownloadfromConnexions:Demo_Integer_Division_and_Modulus.cpp 8 4.7Practice4:OftenUsedDataTypes 9 4.7.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Designaprogram,toinclude:understandingtheproblem,completingInternetresearchasappropriate, createapseudocodedocumentandcreateatestdatadocument. 3.WritetheC++codeforaprogramusingappropriateplanningdocumentationthatyouoranotherhas designed. 4.7.2MemoryBuildingActivities Linkto:MBA04 10 4.7.3Exercises Exercise4.3 Solutiononp.57. Answerthefollowingstatementsaseithertrueorfalse: 1.Integerdatatypesarestoredwithamantissaandanexponent. 2.Stringsareidentiedbysinglequotemarks. 3.Anoperandisavaluethatreceivestheoperator'saction. 4.Arithmeticassignmentisashorterwaytowritesomeexpressions. 5.Integerdivisionisrarelyusedincomputerprogramming. 4.7.4MiscellaneousItems Noneatthistime. 4.7.5LabAssignment 4.7.5.1CreatingaFolderorSub-FolderforChapter04Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: 8 Seetheleat 9 Thiscontentisavailableonlineat. 10 Seetheleat

PAGE 64

56 CHAPTER4.4.OFTENUSEDDATATYPES Chapter_04withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 4.7.5.2DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. TheProblem/TaskIhaveafriendwhoisvisitingfromEuropeandhedoesnotunderstandFahrenheit temperatures.WeneedtowriteaprogramthatallowshimtoenterthetemperatureinFahrenheitas announcedonTVorradioandconvertittoCelsius.Clue1:Fahrenheitwaterfreezesat32degrees andboilsat212degrees.Celsiuswaterfreezesazerodegreesandboilsat100degrees.Google theinternethowtoconvertFahrenheittoCelsiusifyouneedmorehelp.Clue2:Youcanalsouse Internetsitestodoaconversionandthuscreateyourtestdata. Youonlyneedtwovariablesinthisprogram:FahrenheitandCelsiusbothofwhichshouldbethe integerdatatype.WhenyouconverttheFahrenheittoCelsiusyouwillneedtouseaoating-point expressiondoingoating-pointcalculationsforprecision.Additionallywewanttoroundupordown theCelsiusanswerbyadding0.5tothecalculationexpression. Withinyoursub-folder:Chapter_04youwillneedtocreatethreeles: Lab_04_Pseudocode.txt and Lab_04_Test_Data.txt and Lab_04.cpp NOTE:Itwillbeeasiertocopysomepreviousles fromanotherassignmentandusethosecopiesbyrenamingthemandmodifyingthemasappropriate. Theprofessorisexpectingtheitemsyoucreatetohaveasimilarformattothosewehavebeenusing inthecourse. Createyourpseudocode,testdataandsourcecodeles. Buildcompileandrunyourprogram.Youhavesuccessfullywrittenthisprogramwhenitrunswith yourtestdataandgivesthepredictedresults. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 4.7.6Problems 4.7.6.1Problem04aInstructions Decideonthedatatypeandidentiernamesforthefollowing: Problem:Amen'sclothingstorethatcaterstotheveryrichwantstocreateadatabaseforitscustomers thatrecordsclothingmeasurements.Theyneedtorecordinformationforshoes,socks,pants,dressshirts andcasualshirts.HINT:Youmayneedmorethan5dataitems.

PAGE 65

57 SolutionstoExercisesinChapter4 SolutiontoExercise4.1p.54 Answers: 1.3 2.0 3.3.5becauseoneoftheoperandsisaoating-pointvalue,itisnotintegerdivision SolutiontoExercise4.2p.54 Answers: 1.2 2.5 3."error"becausemostcompilersrequirebothoperandstobeoftheintegerdatatype SolutiontoExercise4.3p.55 Answers: 1.false 2.false 3.true 4.true 5.false

PAGE 66

58 CHAPTER4.4.OFTENUSEDDATATYPES

PAGE 67

Chapter5 5.IntegratedDevelopmentEnvironment 5.1IntegratedDevelopmentEnvironment 1 5.1.1IDEOverview High-levellanguageprogramsareusuallywrittencodedasASCIItextintoasourcecodele.Auniquele extensionExamples:.asm.cob.for.pas.c.cppisusedtoidentifyitasasourcecodele.Asyoucanguess forourexamplesAssembly,COBOL,FORTRAN,Pascal,"C"and"C++"however,theyarejustASCII textlesothertextlesusuallyusetheextensionof.txt.Thesourcecodeproducedbytheprogrammer mustbeconvertedtoanexecutablemachinecodelespecicallyforthecomputer'sCPUusuallyanIntel orIntelcompatibleCPUwithintoday'sworldofmicrocomputers.Thereareseveralstepsingettinga programfromitssourcecodestagetorunningtheprogramonyourcomputer.Historically,wehadtouse severalsoftwareprogramsatexteditor,acompiler,alinkerandoperatingsystemcommandstomakethe conversionandrunourprogram.However,todayallthosesoftwareprogramswiththeirassociatedtasks havebeen integrated intooneprogramusuallycalledacompiler.However,thisonecompilerprogramis reallymanysoftwareitemsthatcreatean environment usedbyprogrammersto develop software.Thus thename: IntegratedDevelopmentEnvironment orIDE. ThefollowinggureshowstheprogressionofactivityinanIDEasaprogrammerentersthesourcecode andthendirectstheIDEtocompileandruntheprogram. 1 Thiscontentisavailableonlineat. 59

PAGE 68

60 CHAPTER5.5.INTEGRATEDDEVELOPMENTENVIRONMENT Figure5.1: IntegratedDevelopmentEnvironmentorIDE UponstartingtheIDEsoftwaretheprogrammerusuallyindicateshewantstoopenaleforeditingas sourcecode.Astheymakechangestheymighteitherdoa"saveas"or"save".Whentheyhavenished enteringthesourcecode,theyusuallydirecttheIDEto"compile&run"theprogram.TheIDEdoesthe followingsteps: 1.Ifthereareanyunsavedchangestothesourcecodeleithasthe testeditor savethechanges. 2.The compiler opensthesourcecodeleanddoesits rststep whichisexecutingthe pre-processor compilerdirectivesandotherstepsneededtogetthelereadyforthesecondstep.The#includewill insertheaderlesintothecodeatthispoint.Ifitencountersanerror,itstopstheprocessandreturns theusertothesourcecodelewithinthetexteditorwithanerrormessage.Ifnoproblemsencountered itsavesthesourcecodetoatemporarylecalledatranslationunit. 3.The compiler opensthetranslationunitleanddoesits secondstep whichis converting the programminglanguagecodetomachineinstructionsfortheCPU,adataareaandalistofitemsto beresolvedbythelinker.Anyproblemsencountedusuallyasyntaxorviolationoftheprogramming languagerulesstopstheprocessandreturnstheusertothesourcecodelewithinthetexteditor withanerrormessage.Ifnoproblemsencountereditsavesthemachineinstructions,dataareaand linkerresolutionlistasanobjectle.

PAGE 69

61 4.The linker openstheprogramobjectleandlinksitwiththelibraryobjectlesasneeded.Unlessall linkeritemsareresolved,theprocessstopsandreturnstheusertothesourcecodelewithinthetext editorwithanerrormessage.Ifnoproblemsencountereditsavesthelinkedobjectsasanexecutable le. 5.TheIDEdirectstheoperatingsystem'sprogramcalledthe loader toloadtheexecutableleintothe computer'smemoryandhavetheCentralProcessingUnitCPUstartprocessingtheinstructions.As theuserinteractswiththeprogram,enteringhistestdata,hemightdiscoverthattheoutputsarenot correct.Thesetypesoferrorsarecalledlogicerrorsandwouldrequirehimtoreturntothesource codetochangethealgorithm. 5.1.2ResolvingErrors Despiteourbesteortsatbecomingperfectprogrammers,wewillcreateerrors.Solvingtheseerrorsis knownas debugging yourprogram.Thethreetypesoferrorsintheorderthattheyoccurare: 1.Compiler 2.Linker 3.Logic Therearetwotypesofcompilererrors;pre-processorststepandconversionndstep.Areviewof Figure1aboveshowsthefourarrowsreturningtothesourcecodesothattheprogrammercancorrectthe mistake. Duringtheconversionndstepthecompliermightgivea warning messagewhichinsomecasesmay notbeaproblemtoworryabout.Forexample:Datatypedemotionmaybeexactlywhatyouwantyour programtodo,butmostcompilersgiveawarningmessage.Warningsdon'tstopthecompilingprocessbut astheirnameimplies,theyshouldbereviewed. ThenextthreeguresshowIDEmonitorinteractionforthe BloodshedDev-C++5compiler/IDE .

PAGE 70

62 CHAPTER5.5.INTEGRATEDDEVELOPMENTENVIRONMENT Figure5.2: CompilerErrortheredlineiswherethecomplierstopped

PAGE 71

63 Figure5.3: LinkerErrornoredlinewithanerrormessagedescribinglinkingproblem

PAGE 72

64 CHAPTER5.5.INTEGRATEDDEVELOPMENTENVIRONMENT Figure5.4: LogicErrorfromtheoutputwithinthe"BlackBox"area 5.1.3DemonstrationPrograminC++ 5.1.3.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 5.1.3.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesorucecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Pre_Processor_Compiler_Errors.cpp 2 DownloadfromConnexions:DemoCompiler_Conversion_Errors.cpp 3 2 Seetheleat 3 Seetheleat

PAGE 73

65 DownloadfromConnexions:Demo_Linker_Errors.cpp 4 DownloadfromConnexions:Demo_Logic_Errors.cpp 5 5.1.4Denitions Denition5.1:texteditor AsoftwareprogramforcreatingandeditingASCIItextles. Denition5.2:compiler Convertssourcecodetoobjectcode. Denition5.3:pre-processor Therststepthecomplierdoesinconvertingsourcecodetoobjectcode. Denition5.4:linker Connectsorlinksobjectlesintoanexecutablele. Denition5.5:loader PartoftheoperatingsystemthatloadsexecutablelesintomemoryanddirecttheCPUtostart runningtheprogram. Denition5.6:debugging Theprocessofremovingerrorsfromaprogram.1compiler2linker3logic Denition5.7:warning Acompileralertthattheremightbeaproblem. 5.2StandardInputandOutput 6 5.2.1GeneralDiscussion EverytaskwehavethecomputerdohappensinsidethecentralprocessingunitCPUandtheassociated memory.OnceourprogramisloadedintomemoryandtheoperatingsystemdirectstheCPUtostart executingourprogrammingstatementsthecomputerlookslikethis: 4 Seetheleat 5 Seetheleat 6 Thiscontentisavailableonlineat.

PAGE 74

66 CHAPTER5.5.INTEGRATEDDEVELOPMENTENVIRONMENT Figure5.5: CPUMemoryInput/OutputDevices Ourprogramnowlocatedinthememoryhasbasicallytwoareas: Machineinstructionsourinstructionsforwhatwewantdone Datastorageourvariablesthatweusinginourprogram Oftenourprogramcontainsinstructionstointeractwiththeinput/outputdevices.Weneedtomovedata intoreadand/oroutofwritethememorydataarea.A device isapieceofequipmentthatiselectronically connectedtothememorysothatdatacanbetransferredbetweenthememoryandthedevice.Historically thiswasdonewithpunchedcardsandprintouts.Tapedriveswereusedforelectronicstorage.Withtime wemigratedtousingdiskdrivesforstoragewithkeyboardsandmonitorswithmonitoroutputcalledsoft copyreplacingpunchcardsandprintoutscalledhardcopy. Mostcomputeroperatingsystemsandbyextensionprogramminglanguageshaveidentiedthekeyboard asthe standardinputdevice andthemonitorasthe standardoutputdevice .Oftenthekeyboardand monitoraretreatedasthedefaultdevicewhennootherspecicdeviceisindicated.

PAGE 75

67 5.2.2StandardI/OwithinC++ ThedevelopersoftheC++programminglanguagedecidedtoprovidesomeofthemoretechnicalcodeneeded tointeractwiththeoperatingsystemandtheI/Odevices.Inthefollowingexampletheincludedirective insertsalethatcontainscodefromthe Input-OutputStream library.Thislecontainsnecessarycode touse cout and cin forsendingdatatothemonitororgettingdatafromthekeyboard. #include < iostream > Youshouldthinkof cout and cin asbeinglocationsthatyoucansendtoorreceivedatafrom;similarin concepttoanyothervariablestoragelocationwithinthedataareaofourprogram.TheC++programming languagehastwooperatorstouseinconjunctionwithI/Odevices. Action C++operatorsymbol Usedwith insertionoperatorwrite apairoflessthansymbols cout extractionoperatorread apairofgreaterthansymbols cin Table5.1 Considerthefollowingcode: Example5.1:InsertionandExtraction intage1;//variablesetup thenlateroninourprogram cout n nEntertheageofthefirstperson--> :"; cin age1; Usingthe cout theprogrammerdisplaysorinsertsapromptingmessageonthemonitorfortheuserto see.Usingthe cin theusertypesanintegervalueandhitstheenterkeyandthecomputerextractsthevalue fromthekeyboardandstoresitintothevariablenamedage1.Withinthecomputeralldataarestoredas numbersandthuspartofthetechnicalcodeprovidedbythedevelopersoftheC++programminglanguage thatiswithinthe Input-OutputStream libraryconvertsdatafromnumberstothosesymbolsweareused toseeingashumansandviceversa.Example:Iftheuserenteredthenumeraldigits57andhittheenter keytheextractionoperatorwouldconvertthe57intoabinarynumberandmovethebinarynumberinto theintegerstorageplacenamedage1. The cout whichusesthestandardoutputdevicedoesnotformattheoutputintoaGraphicalUser InterfaceGUIwhereyouhaveamousetouse.AmodernoperatingsystemusingGUInormallyopensa blackscreenoutputbox thatwouldbesimilartohowthemonitorwasusedwhenrstdevelopedinthe 1960's.Thatisthedefaultofhow cout isnormallyimplementedbymostcompilers. Theoutputmessagehasauniqueitemworthmentioning.Attheveryfrontofthemessageisabackslash followedbythelettern.Theydonotgetprintedonthemonitor.Itisaspecialcodecalledaprinter escape code tellingtheprintertogotoanewline.Printer!Ithoughtwewereusingamonitor?Wearebutthe codeisaleftoverfromtheearlydaysofprinteroutput.Thebackslashtellstheprinterormonitorthatthe nextletterisacommand.Theletternisusedfortellingtheprinterormonitortogotothefrontofanew line. 5.2.3Denitions Denition5.8:device Apieceofequipmentthatiselectronicallyconnectedtothememorysothatdatacanbetransferred betweenthememoryandthedevice.

PAGE 76

68 CHAPTER5.5.INTEGRATEDDEVELOPMENTENVIRONMENT Denition5.9:standardinput Thekeyboard. Denition5.10:standardoutput Themonitor. Denition5.11:insertion Akawritingorsendingdatatoanoutputdevice. Denition5.12:extraction Akareadingorgettingdatafromaninputdevice. Denition5.13:escapecode Ancodedirectinganoutputdevicetodosomething. 5.3CompilerDirectives 7 5.3.1GeneralDiscussion A compilerdirective isaninstructiontothecompilertocompleteataskbeforeformallystartingtocompile theprogram,thustheyaresometimescalledpre-processordirectives.Amongotheritems,duringthepreprocessorstepthecompilerislookingforcompilerdirectivesandprocessesthemastheyareencountered. Aftercompletingthetasksasdirected,thecompilerproceedstoitssecondstepwhereitchecksforsyntax errorsviolationsoftherulesofthelanguageandconvertsthesourcecodeintoanobjectcodethatcontains machinelanguageinstructions,adataarea,andalistofitemstoberesolvedwhenheobjectleislinkedto otherobjectles. WithinC++thepoundsymbolor#astherstcharacterofalineindicatesthatthenextwordisa directiveorcommandwordtobeevaluated.Thetwomostcommoncompilerdirectivesare: 1. include withtheitemfollowingincludebeingthenameofalethatistobeinsertedatthatplace inthele.Thelesareoftencalled"HeaderFiles"becausetheincludedirectiveisnormallyinserted towardthetopoftheleattheheadasoneoftherstitems. 2. dene withtheitemfollowedbyanidentiernameandavalue.Thisidentiernameandvalueis storedbythecompilerandwhenitencounterstheidentiernameintheprogramitsubstitutesthe valuefortheidentiername. Inthefollowingexampletheincludedirectiveisinsertingalethatcontainscodefromthe Input-Output Stream library.Thislecontainsnecessarycodetousecoutandcinforsendingdatatothemonitoror gettingdatafromthekeyboard. #include < iostream > Inthenextexamplethedenedirectiveisbeingusedtohandleaconstantcalledadenedconstant. Example5.2:SubtitutingPI #definePI3.14159 ....LateronintheprogramwhenitencountersPI ....itwillreplaceorsubstitutePIwiththevalue3.14159 ....Forexample: area_circle=radius*radius*PI; wouldbecome: area_circle=radius*radius*3.14159; 7 Thiscontentisavailableonlineat.

PAGE 77

69 Ofnote,compilerdirectivesinC++donothaveasemi-colonafterthem.WithinC++programming instructionsorstatementsendwithasemi-colon,butnotcompilerdirectives. 5.3.2Denitions Denition5.14:compilerdirective Aninstructiontothecompilertocompleteataskbeforeformallystartingtocompiletheprogram. Denition5.15:include Acompilerdirectivetoinsertthecontentsofaleintotheprogram. 5.4Practice5:IntegratedDevelopmentEnvironment 8 5.4.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.BeabletolistthecategoriesandgiveexamplesoferrorsencounteredwhenusinganIntegratedDevelopmentEnvironmentIDE. 3.WritetheC++codeforaprogramusingappropriateplanningdocumentationthatyouoranotherhas designed. 5.4.2MemoryBuildingActivities Linkto:MBA05 9 5.4.3Exercises Exercise5.1 Solutiononp.72. Answerthefollowingstatementsaseithertrueorfalse: 1.IDEmeansIntegerDivisionExpression. 2.MostmoderncompilersarereallyanIDEtypeofsoftware,notjustacompiler. 3.cinandcoutareusedforthestandardinputandoutputinC++. 4.Programmingerrorsareextremelyeasytounderstandandx. 5.AllC++programswillhaveatleastoneincludetypeofcompilerdirective. 5.4.4MiscellaneousItems Noneatthistime. 8 Thiscontentisavailableonlineat. 9 Seetheleat

PAGE 78

70 CHAPTER5.5.INTEGRATEDDEVELOPMENTENVIRONMENT 5.4.5LabAssignment 5.4.5.1CreatingaFolderorSub-FolderforChapter05Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_05withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 5.4.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Solution_Lab_02_Pseudocode.txt 10 DownloadfromConnexions:Solution_Lab_02_Test_Data.txt 11 5.4.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. Copyintoyoursub-folder:Chapter_05oneofthesourcecodelistingsthatwehaveused.Wesuggest theLab01sourcecodeandrenamethecopy: Lab_05.cpp ModifythecodetofollowtheSolution_Lab_02_Pseudocode.txtle. Buildcompileandrunyourprogram.Youhavesuccessfullywrittenthisprogramifwhenitrunsand youusethetestdata[usethetestdataassuppliedasthesolutionforLab02]itgivesthepredicted results. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 5.4.6Problems 5.4.6.1Problem05aInstructions ListanddescribewhatmightcausethefourtypesoferrorsencounteredinaprogramusinganIntegrated DevelopmentEnvironmentsoftwareproduct. 5.4.6.2Problem05bInstructions IdentifyfourproblemswiththiscodelistingHINT:Thefourtypesoferrorsencounteredinaprogram usinganIntegratedDevelopmentEnvironmentsoftwareproduct. Example5.3:C++SourceCodeListing //****************************************************** //Filename:Compiler_Test.cpp //Purpose:Averagetheagesoftwopeople 10 Seetheleat 11 Seetheleat

PAGE 79

71 //Author:KenBusbee; KennethLeroyBusbee //Date:Jan5,2009 //Comment:Mainideaistobeableto //debugandrunaprogramonyourcompiler. //****************************************************** //HeadersandOtherTechnicalItems #include < iostrern > usingnamespacestd; //FunctionPrototypes voidpausevoid; //Variables intage1; intage2; doubleanswear; //****************************************************** //main //****************************************************** intmainvoid { //Input cout n nEntertheageofthefirstperson--> :"; cin age1; cout n nEntertheageofthesecondperson-> :"; cin age2; //Process answer=age1+age2/3.0; //Output cout n nTheaverageoftheiragesis-------> :"; cout answer; pause; return0; } //****************************************************** //EndofProgram //******************************************************

PAGE 80

72 CHAPTER5.5.INTEGRATEDDEVELOPMENTENVIRONMENT SolutionstoExercisesinChapter5 SolutiontoExercise5.1p.69 Answers: 1.false 2.true 3.true 4.false 5.true

PAGE 81

Chapter6 6.ProgramControlFunctions 6.1PseudocodeExamplesforFunctions 1 6.1.1Concept Nostandardforpseudocodesyntaxexists.However,therearesomecommonlyfollowedconventionstohelp makepseudocodewrittenbyoneprogrammereasilyunderstoodbyanotherprogrammer.Thefollowing describesamethodforusingpseudocodeforfunctionsthatwouldbeunderstoodbyprogrammers.Five conceptsare: Usea beginningphraseword tostartthefunction Usea communicationphraseword toidentifytheitemsbeingpassedintothefunction Useindentationtoshowtheactionpartofthefunction Usea communicationphraseword toidentifytheitemsbeingpassedoutofthefunction Usean endingphraseword toendthefunction Usea callingphraseword todirectyourprogramtouseafucntion Thefollowingisasuggestedoutlineoffunctionphrasewords: Item/Purpose StartingPhraseWord EndingPhraseWord Beginning Function N/A CommunicationIn PassIn: none Action N/A N/A CommunicationOut PassOut: none Ending N/A Endfunction CallingaFunction Call: none Table6.1 6.1.2Examples Herearesomeexamplesshowingfunctionsdenedinpseudocodeusingourconventionsasdescribedabove. Example6.1:pseudocode:Functionwithnoparameterpassing 1 Thiscontentisavailableonlineat. 73

PAGE 82

74 CHAPTER6.6.PROGRAMCONTROLFUNCTIONS Functionclearmonitor PassIn:nothing Directtheoperatingsystemtoclearthemonitor PassOut:nothing Endfunction Example6.2:pseudocode:Functionwithparameterpassing Functiondelayprogramsoyoucanseethemonitor PassIn:integerrepresentingtenthsofasecond Usingtheoperatingsystemdelaytheprogram PassOut:nothing Endfunction Example6.3:pseudocode:Functionmaincallingtheclearmonitorfunction Functionmain PassIn:nothing Doingsomelinesofcode Call:clearmonitor Doingsomelinesofcode PassOut:valuezerototheoperatingsystem Endfunction 6.1.3Denitions Denition6.1:phraseword Wordsusedtomakepseudocodelogiccleartoanyreader. 6.2HierarchyorStructureChart 2 6.2.1Overview The hierarchychart alsoknownasa structurechart showstherelationshipofvariousunits.Its namecomesfromitsgeneraluseinshowingtheorganizationorstructureofabusiness.ThePresident atthetop,thenvicepresidentsonthenextlevel,etc.Withinthecontextofacomputerprogramitshows therelationshipbetweenmodulesorfunctions.Detaillogicoftheprogramisnotpresented.Itdoes representtheorganizationofthefunctionsusedwithintheprogramshowingwhichfunctionsarecallingon asubordinatefunction.Thoseabovearecallingthoseonthenextleveldown. Hierarchychartsarecreatedbytheprogrammertohelpdocumentaprogram.Theyconveythebig pictureofthemodulesorfunctionsusedinaprogram. 2 Thiscontentisavailableonlineat.

PAGE 83

75 Figure6.1: HierarchyorStructurechartforaprogramthathasvefunctions. 6.2.2Denitions Denition6.2:hierarchychart Conveytherelationshiporbigpictureofthevariousfunctionsinaprogram. Denition6.3:structurechart Anothernameforahierarchychart. 6.3ProgramControlFunctions 3 6.3.1PrerequisiteMaterial CriticaltothismoduleisthereviewofseveralConnexionsmodules: 1.m_18861Titled:ModularizationandC++ProgramLayout 3 Thiscontentisavailableonlineat.

PAGE 84

76 CHAPTER6.6.PROGRAMCONTROLFUNCTIONS 2.m_19136Titled:PseudocodeExamplesforFunctions 3.m_18682Titled:HierarchyorStructureChart Youshouldreviewthesematerialsbeforeproceeding.Ifyouareviewingthismoduleon-line,linkstothese itemsareinthe"Links"boxtoyourright. 6.3.2ConceptofModularization Theconceptiseverywherepresentintherealworldaboutus.Simplyputitisto takealargecomplicatedproblemandtodivideitintosmallermanageablepieces .Thehierarchychartofanylarge organizationgovernmentunit,company,university,hospital,etc.willshowlevelsofpeoplewithjobtitles thatindicateadierentareaofresponsibility.Eachpersonisasmallpieceoftheoverallworkingsofthe organization.Eachpersoncanconcentrateontheiruniquetalentortasktomakesureitworksproperly. Collectivelytheyaccomplishthegoalsoftheorganization. Additionally,theconcepthasbeenaroundforalongtime.Avillageof300yearsagohadfarmers,tailors, butchers,blacksmiths,etc.Manufacturingisaprimeexampleofnotjustworkbeingmodularizedbutthe productitselfisviewedintermsofmodulesorsystemsExampleofaautomobile:engine,steering,brakes, etc.. Theworldofcomputers,bothhardwareequipmentandsoftwarecomputerprograms,alsousesthis modularconcept.Thus,theconceptmigratestoasinglecomputerprogram;allowingustomodularizethe programintomanageabletaskscalledfunctions. 6.3.3ProgramControlFunctions ProgramControlfunctionsnormallytodonotcommunicateinformationtoeachotherbutusea common area forvariablestorage.Therulesforhowdataiscommunicatedinandoutofafunctionvarygreatlyby programminglanguage,buttheconceptisthesame.Thedataitemspassedorcommunicatedarecalled parameters.Thusthewording: parameterpassing .However,withprogramcontrolfunctionsweuse thedatacommunicationoptionof nocommunicationinwithnocommunicationout .Ourdata variablesandconstantsareplacedinacommonareaavailabletoallfunctionscalledglobalscope. Theidentiernamesforprogramcontrolfunctionsusuallyimplyatasktobeaccomplished,suchas get-data,process-dataorshow-results.Asyoulearntowritemorecomplicatedprogramsthenumberof linesofcodewillincrease.Prudencedictatesthatitwouldbebenecialtodividetheprogramintofunctions thatperformuniquetasks.Thelargertheprogramthemoreneedformodularizationorcreatingofprogram controlfunctions. Dependingontheprogramminglanguage,thereisaformalwayto: 1.deneafunctionit's denition orthecodeitwillexecute 2. call afunction 3.declareafunctiona prototype isadeclarationtoacomplier Oneoftheeasierwaystounderstandprogramcontrolfunctionistoviewanexample.Evenifyoudon't knowtheC++programminglanguage,youcanstudythematerialstohelpunderstandthemodularization process. 6.3.4DemonstrationPrograminC++ 6.3.4.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs

PAGE 85

77 Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 6.3.4.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonsomeofthelinksandselect"SaveTargetAs"inordertodownloadsomeoftheles. Followingthemethodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodeles inconjunctionwithotherlearningmaterials. DownloadfromConnexions:Demo_Program_Control_Functions_before_Compiler_Test.cpp 4 DownloadfromConnexions:Demo_Program_Control_Functions_Pseudocode.txt 5 DownloadfromConnexions:Demo_Program_Control_Functions_Hierarchy_Chart.jpg 6 DownloadfromConnexions:Demo_Program_Control_Functions.cpp 7 6.3.4.3StudytheMaterialsCollectivelytoUnderstandModularization Thefouritemsrepresentaprogressionfromnomodularizationtomodularization: 1.Programcodebeforeitismodularized 2.Modularizedpseudocodeandahierarchychartfortheprogram 3.Programcodethathasbeenmodularized Thesimplicityoftheprogramshouldnotbeconsideredduringthisreview.Itisobviousthattheprogram doesnotneedmodularization.Theexampleistoshowordemonstratehowtomodularizeaprogramfor programcontrol. 6.3.5Denitions Denition6.4:commonarea Anareaoftheprogramwherevariablesandconstantsaredenedsothattheyareavailabletoall functions. 6.4VoidDataType 8 6.4.1GeneralDiscussion The voiddatatype hasnovaluesandnooperations.It'sadatatypethatrepresentsthelackofadata type. C++ReservedWord void Represent Nothing Size N/AorNone NormalSignage N/A DomainValuesAllowed None Table6.2 4 Seetheleat 5 Seetheleat 6 Seetheleat 7 Seetheleat 8 Thiscontentisavailableonlineat.

PAGE 86

78 CHAPTER6.6.PROGRAMCONTROLFUNCTIONS Thisdatatypewasaddedinthetransitionfrom"C"to"C++".In"C"bydefaultafunctionreturnedan integerdatatype.Somefunctionsdon'treturnavalueofanykind.Thus,theneedtohaveadatatypethat indicates nothing isbeingreturned.Thevoiddatatypeismainlyusedinthedenitionandprototypingof functionstoindicatethateithernothingisbeingpassedinand/ornothingisbeingpassedout. 6.4.2Denitions Denition6.5:voiddatatype Adatatypethathasnovaluesoroperatorsandisusedtorepresentnothing. 6.5DocumentationandMakingSourceCodeReadable 9 6.5.1GeneralDiscussion Wearegoingtoconsiderasimpleprogramthatmightbeusedfortestingacompilertomakesurethatitis installedcorrectly. Example6.4:Compiler_Test.cppsourcecode //****************************************************** //Filename:Compiler_Test.cpp //Purpose:Averagetheagesoftwopeople //Author:KenBusbee; KennethLeroyBusbee //Date:Jan5,2009 //Comment:Mainideaistobeableto //debugandrunaprogramonyourcompiler. //****************************************************** //HeadersandOtherTechnicalItems #include < iostream > usingnamespacestd; //FunctionPrototypes voidpausevoid; //Variables intage1; intage2; doubleanswer; //****************************************************** //main //****************************************************** intmainvoid 9 Thiscontentisavailableonlineat.

PAGE 87

79 { //Input cout n nEntertheageofthefirstperson--> :"; cin age1; cout n nEntertheageofthesecondperson-> :"; cin age2; //Process answer=age1+age2/2.0; //Output cout n nTheaverageoftheiragesis-------> :"; cout answer; pause; return0; } //****************************************************** //pause //****************************************************** voidpausevoid { cout n n n n"; system"PAUSE"; cout n n n n"; return; } //****************************************************** //EndofProgram //****************************************************** Withintheprogrammingindustrythereisadesiretomakesoftwareprogramseasytomaintain.Thedesire centersinmoney.Simplyput,itcostslessmoneytomaintainawellwrittenprogram.Oneimportantaspect ofprogrammaintenanceismakingsourcecodelistingsclearandaseasytoreadaspossible.Tothatendwe willconsiderthefollowing: 1.Documentation 2.VerticalAlignment 3.AppropriateuseofComments 4.BannersforFunctions 5.BlockMarkersonLinesbyThemselves 6.IndentBlockMarkers 7.MeaningfulIdentierNamesConsistentlyTyped 8.AppropriateuseofTypedef Let'scovereachiteminmoredetail.

PAGE 88

80 CHAPTER6.6.PROGRAMCONTROLFUNCTIONS 6.5.1.1Documentation Documentationisusuallyplacedatthetopoftheprogramusingseveralcommentlines.Theamountof informationwouldvarybasedontherequirementsorstandardsofthecompanywhoispayingitsemployees orindependentcontractorstowritethecode.Noticetheindicationofrevisiondates. 6.5.1.2VerticalAlignment Youseethiswithinthedocumentationarea.Alloftheitemsarealignedupwithinthesamecolumn.This verticalalignmentoccursagainwhenthevariablesaredened.Whendeclaringvariableorconstantsmany textbooksputseveralitemsononeline;likethis: Example6.5:CommonTextbookDeningofVariables floatlength,width,height,price_gal_paint,total_area,total_cost; intcoverage_gal_paint,total_gal_paint; Howevercommonthisisintextbooks,itwouldgenerallynotbeacceptabletostandardsusedinmost companies.Youshoulddeclareeachitemonitsownline;likethis: Example6.6:ProperDeningofVariableswithVerticalAlignment floatlength; floatwidth; floatheight; floatprice_gal_paint; intcoverage_gal_paint; floattotal_area; inttotal_gal_paint; floattotal_cost; Thismethodofusingoneitemperlineismorereadablebyhumans.Itisquickertondanidentiername, becauseyoucanreadthelistverticallyfasterthansearchinghorizontally.Someprogrammerslistthemin alphabeticorder,especiallywhenthenumberofvariablesexceedsabouttwenty. Thelinesofcodeinsideeitherfunctionarealsoalignedverticallyandindentedtwospacesfromtheleft. Theindentationhelpssettheblockovisually. 6.5.1.3AppropriateuseofComments Youcanseethroughthesourcecodeshortlittlecommentsthatdescribeanareaorsection.Notetheuseof input,processingandoutputwhicharepartoftheIPOconceptwithintheprogramdesign. 6.5.1.4BannersforFunctions Notetheuseofcommentsintheformofabannerbeforeeachfunction. Example6.7:CommentsasaBanner

PAGE 89

81 //****************************************************** //main //****************************************************** Thefunctionnameisplacedwithtwolinesofasterisks.Itmakesitextremelyeasytondeachfunction denitionbecauseyoudon'thavetoreadthefunctionstoseewheretheoneendsandthenextonebegins. Youcanquicklyreadthefunctionnameswithinthebanners. 6.5.1.5BlockMarkersonLinesbyThemselves Withinmanylanguagesthereisamethodtoidentifyagroupofprogrammingstatementsasaunit.With C++thefunctionsuseasetofsymbols,thebraces{},toidentifyablockofcode,sometimesreferredto asacompoundstatement.Bracesareusedinotheraspectsofprograms,butfornowwewilllookatthis simpleexample.Thesebraceshaveatendencytocauseproblems,especiallywhentheydon'thaveaproper openingbraceassociatedwithaproperclosingbrace.Tosolvethatproblemmanyprogrammerssimplyput abraceonalinebyitselfandmakesuretheopeningbraceandclosingbraceareinthesameverticalcolumn. 6.5.1.6IndentBlockMarkers Ablockofcodeassociatedwithafunctionorwithacontrolstructureisindentedtwoorthreespaces.When blocksofcodearenestedeachnestingisindentedtwoorthreespaces.Inourexampleabovetheblocksof codeforthefunctiondenitionsareindentedtwospaces. 6.5.1.7MeaningfulIdentierNamesConsistentlyTyped Asthenameimplies"identiernames"shouldclearlyidentifywhoorwhatyouaretalkingabout.Calling youspouse"Snooky"maybemeaningfultoonlyyou.OthersmightneedtoseeherfullnameJane MarySmithtoappropriatelyidentifywhoyouaretalkingabout.Thesameconceptinprogrammingis true.Variables,constants,functions,typedefsandotheritemsshouldusemeaningfulidentiernames. Additionally,thosenamesshouldbetypedconsistentlyintermsofupperandlowercaseastheyareusedin theprogram.Don'tdeneavariableas:Pigandthentypeitlateroninyourprogramas:pig. 6.5.1.8AppropriateuseofTypedef Manyprogramminglanguageshaveacommandthatallowsforthecreationofanidentiernamethat representsadatatype.Thenewidentiernameisdescribedorconnectedtoarealdatatype.Thisfeature isnotdemonstratedinthecodeaboveandisoftenaconfusingconcept.Itisapowerfulwaytohelpdocument aprogramsothatitismeaningful,butisoftenusedbymoreexperiencedprogrammers. 6.5.2Denitions Denition6.6:documentation Amethodofpreservinginformationusefultoothersinunderstandinganinformationsystemor partthereof. Denition6.7:verticalalignment Amethodoflistingitemsverticallysothattheyareeasiertoreadquickly. Denition6.8:comments Informationinsertedintoasourcecodelefordocumentationoftheprogram. Denition6.9:banners Asetofcommentlinesusedtohelpseparatethefunctionsandothersectionsofaprogram.

PAGE 90

82 CHAPTER6.6.PROGRAMCONTROLFUNCTIONS Denition6.10:braces UsedtoidentifyablockofcodeinC++. Denition6.11:indention Amethodusedtomakesectionsofsourcecodemorevisible. Denition6.12:meaningful Arulethatsaysidentiernamesmustbeeasilyunderstoodbyanotherreadingthesourcecode. Denition6.13:consistent Arulethatsaystotypeidentiernamesinupperandlowercaseconsistentlythroughoutyour sourcecode. 6.6Practice6:ProgramControlFunctions 10 6.6.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Givenpseudocode,testdataandsourcecodeofanexistingprogram,modifythepseudocodeandsource codetocreate"programcontrol"functions. 6.6.2MemoryBuildingActivities Linkto:MBA06 11 6.6.3Exercises Exercise6.1 Solutiononp.87. Answerthefollowingstatementsaseithertrueorfalse: 1.Pseudocodehasastrictsetofrulesandisthesameeverywhereinthecomputerprogramming industry. 2.HierarchyChartsandStructureChartsarebasicallythesamething. 3.ProgramControlfunctionsareusedtosimplysubdivideandcontroltheprogram. 4.ThevoiddatatypeisrarelyusedinC++. 5.Makingsourcecodereadableisonlyusedbybeginningprogrammers. 6.6.4MiscellaneousItems Noneatthistime. 10 Thiscontentisavailableonlineat. 11 Seetheleat

PAGE 91

83 6.6.5LabAssignment 6.6.5.1CreatingaFolderorSub-FolderforChapter06Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_06withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 6.6.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Solution_Lab_01.cpp 12 DownloadfromConnexions:Solution_Lab_01_Pseudocode.txt 13 DownloadfromConnexions:Solution_Lab_01_Test_Data.txt 14 DownloadfromConnexions:Solution_Lab_01m_with_Program_Control.cpp 15 DownloadfromConnexions:Solution_Lab_01m_Pseudocode_with_Program_Control.txt 16 DownloadfromConnexions:Solution_Lab_01m_Hierarchy_Chart.jpg 17 DownloadfromConnexions:Solution_Lab_03.cpp 18 DownloadfromConnexions:Solution_Lab_03_Pseudocode.txt 19 DownloadfromConnexions:Solution_Lab_03_Test_Data.txt 20 6.6.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. Navigatetoyoursub-folder:Chapter_06.ReviewtheoriginalLab01materials.Compileandrunthe Lab01sourcecode.ThenreviewandcomparetheoriginalLab01materialstomodularizedLab01 materialstakingnoteoftheconversionto"programcontrol"functions.CompileandruntheLab01m sourcecode.Reviewasneededthecoursematerials.Emailyourprofessorifyouhaveanyquestions. WehavesuppliedthesolutiontotheLab03assignment.ReviewtheLab03assignmentbycompiling andrunningtheLab03sourcecode. YouneedtocopytheLab03sourcecodeleandpseudocodeletomakethefollowingnewles: Lab_06.cpp and Lab_06_Pseudocode.txt ModifytheLab06pseudocodeletoimplementprogramcontrolfunctionsasshowninthedemonstrationmaterials. ModifytheLab06sourcecodeletoimplementprogramcontrolfunctionsasshowninthedemonstrationmaterials. Buildcompileandrunyourprogram.Youhavesuccessfullywrittenthisprogramifwhenitrunsand youusethetestdata[usethesametestdataasusedinLab03]itgivesthesameresultsasLab03. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 12 Seetheleat 13 Seetheleat 14 Seetheleat 15 Seetheleat 16 Seetheleat 17 Seetheleat 18 Seetheleat 19 Seetheleat 20 Seetheleat

PAGE 92

84 CHAPTER6.6.PROGRAMCONTROLFUNCTIONS 6.6.6Problems 6.6.6.1Problem06aInstructions Createahierarchychartforthefollowingpseudocodeexample. Example6.8:pseudocode ****************************************************** Filename:Average_IQ.txt Purpose:AveragetheIQsoftwopeople Author:KenBusbee; KennethLeroyBusbee Date:Jan17,2009 ****************************************************** Functionmain PassIn:nothing Call:get_iqs Call:process_iqs Call:show_average PassOut:zerototheOS Endfunction ******************** Functionget_iqs PassIn:nothing displayamessageaskinguserfortheIQofthefirstperson gettheIQofthefirstpersonfromthekeyboard displayamessageaskinguserfortheIQofthesecondperson gettheIQofthesecondpersonfromthekeyboard PassOut:nothing Endfunction ******************** Functionprocess_iqs PassIn:nothing calculatetheanswerbyaddingthetwoIQsand dividingby2.0 PassOut:nothing Endfunction ******************** Functionshow_average PassIn:nothing displaytheanswerwithanappropriatemessage Call:pause PassOut:nothing Endfunction

PAGE 93

85 ******************** Functionpause PassIn:nothing directtheoperatingsystemtopausetheprogram PassOut:nothing Endfunction ****************************************************** PotentialVariables DataTypeIdentifierName ************************ integeriq1 integeriq2 doubleanswer ****************************************************** Endoffile 6.6.6.2Problem06bInstructions Identifysomeproblemsthatmakethiscode"undocumented","unreadable"orwronginsomeotherway. Example6.9:C++sourcecode //****************************************************** //Author:KenBusbee; 2009KennethLeroyBusbee //Date:Jan17,2009 //****************************************************** #include < iostream > usingnamespacestd; voidpausevoid; intage1,age2; doublexx; //****************************************************** //main //****************************************************** intmainvoid { //Input

PAGE 94

86 CHAPTER6.6.PROGRAMCONTROLFUNCTIONS cout n nEntertheageofthefirstperson--> :"; cin > %gt;age1; cout n nEntertheageofthesecondperson-> :"; cin > %gt;age2; //Process xx=age1+age2/2.0; //Output cout n nTheaverageoftheiragesis-------> :"; cout xx; pause; return0; } voidpausevoid {cout n n n n"; system"PAUSE"; cout n n n n"; return;} //****************************************************** //EndofProgram //******************************************************

PAGE 95

87 SolutionstoExercisesinChapter6 SolutiontoExercise6.1p.82 Answers: 1.false 2.true 3.true 4.false 5.false

PAGE 96

88 CHAPTER6.6.PROGRAMCONTROLFUNCTIONS

PAGE 97

Chapter7 7.SpecicTaskFunctions 7.1SpecicTaskFunctions 1 7.1.1PrerequisiteMaterial CriticaltothismoduleisthereviewoftwoConnexionsmodules: 1.m_18861Titled:ModularizationandC++ProgramLayout 2.m_19145Titled:ProgramControlFunctions Youshouldreviewthesematerialsbeforeproceeding.Ifyouareviewingthismoduleon-line,linkstothese itemsareinthe"Links"boxtoyourright. 7.1.2GeneralConcept ProgramControlfunctionswhichmighthavesimilaridentiernamesusuallyperformslightlydierenttasks inoneprogramtoanother.Lookingattheorganizationalchartorhierarchychartfortwocompanies,both mighthaveavicepresidentofproduction,butproducingautomobilesisdierentthanproducingicecream. Similarbutdierent.Asyougodowndeeperintoanorganizationyoumightndthejobtitleofsecurity guard.Noticethatthesecurityguardattheautomobileplantandthesecurityguardattheicecreamplant haveexactlythesamejob.Infact,theyaremostlikelyinterchangeable.Withinprogrammingwhenatask getsspecicitmightbeuseableinseveralprograms.Thecalculationofleapyearisagoodexample.Needed forthevericationofdates,isthereoristherenota29 th ofFebruaryforthisyear.Neededinthousandsof programs. 7.1.3SpecicTaskFunctions TocreategoodSpecicTaskfunctionsyouneedtodoallcommunicationneededviaparameterpassing.Thus allprogramsthatwillusethefunctionwillcommunicateinpreciselythesameway.Inourleapyearexample, youwouldcommunicateintothefunctiontheyearandthefunctionwouldreturnthecommunicationoftrue orfalse;meaningitisaleapyearandthereisa29 th ofFebruarytrueoritisnotaleapyearfalse. Theabilitytomodularizeourprogramintospecictaskfunctionsmeansthatwecanwritethespecic taskfunctiononcemakingsureitworkscorrectly,thenreuseitoverandoverinmanyprograms.Asyou canguessthereisabalance.Mostprogramswillhavesomeprogramcontrolfunctionsandsomespecic taskfunctions.Thekeytodecidingifthefunctionshouldbeaspecictaskfunctionisusuallyrootedinthe uniquenessofthetasksothatitcanbeusedinmanyprograms.Specictaskfunctionsoncecreatedare usuallyplacedintoa userdenedlibrary thensharedwithothersforuseinmanyprograms. 1 Thiscontentisavailableonlineat. 89

PAGE 98

90 CHAPTER7.7.SPECIFICTASKFUNCTIONS 7.1.4Denitions Denition7.1:userdenedlibrary Alecontainingspecictaskfunctionscreatedbyindividualstobeusedinmanyprograms. 7.2GlobalvsLocalDataStorage 2 7.2.1GeneralDiscussion Theconceptofglobalandlocaldatastorageisusuallytiedtotheconceptofscope.Scopeistheareaofthe programwhereanitembeitvariable,constant,function,etc.thathasanidentiernameisrecognized.In ourdiscussionwewilluseavariableandtheplacewithinaprogramwherethevariableisdeneddetermines itsscope. Globalscope andbyextensionglobaldatastorageoccurswhenavariableisdened"outsideofa function".Whencompilingtheprogramitcreatesthestorageareaforthevariablewithintheprogram's dataareaaspartoftheobjectcode .Theobjectcodehasamachinecodepiece,adataareaandlinker resolutioninstructions.Becausethevariablehasglobalscopeitisavailabletoallofthefunctionswithin yoursourcecode.Itcanevenbemadeavailabletofunctionsinotherobjectmodulesthatwillbelinked toyourcode;howeverwewillforgothatexplanationnow.Akeywordingchangeshouldbelearnedatthis point.Althoughthevariablehasglobalscope,technicallyitisavailableonlyfrom thepointofdenition totheendoftheprogramsourcecode .Thatiswhymostvariablewithglobalscopeareplacednear thetopofthesourcecodebeforeanyfunctions.Thiswaytheyareavailabletoallofthefunctions. Localscope andbyextensionlocaldatastorageoccurswhenavariableisdened"insideofafunction". Whencompiling,thecompilercreatesmachineinstructionsthatwilldirectthecreationofstoragelocations onanareaknownasthe stackwhichispartofthecomputer'smemory .Thesememorylocations existuntilthefunctioncompletesitstaskandreturnstoitscallingfunction.Inassemblylanguagewetalk aboutitemsbeingpushedontothestackandpoppedothestackwhenthefunctionterminates.Thus the,stackisareusableareaofmemorybeingusedbyallfunctionsandreleasedasfunctionsterminate. Althoughthevariablehaslocalscope,technicallyitisavailableonlyfrom thepointofdenitiontothe endofthefunction .The parameterpassing ofdataitemsintoafunctionestablishesthemaslocal variables.Additionally,anyothervariablesorconstantsneededbythefunctionusuallyoccurnearthetop ofthefunctiondenitionsothattheyareavailableduringtheentireexecutionofthefunction'scode. Scopeisanimportantconcepttomodularization. ProgramControl functionsusuallyuseglobalscope forvariablesandconstantsplacingthemnearthetopoftheprogrambeforeanyfunctions. SpecicTask functionsuseonlylocalscopevariablesbypassingdataasneededintothefunctionwithparameterpassing andcreatinglocalvariablesandconstantsasneeded.Anyinformationthatneedstobecommunicatedback tothecallingfunctionisagaindoneviaparameterpassing.This closedcommunicationsmodel that passesalldataintoandoutofafunctioncreatesanimportantpredecessorconceptfor encapsulation which isusedinobjectorientedprogramming. 7.2.2Denitions Denition7.2:globalscope Datastoragedenedoutsideofafunction. Denition7.3:localscope Datastoragedenedinsideofafunction. Denition7.4:dataarea Apartofanobjectcodeleusedforstorageofdata. 2 Thiscontentisavailableonlineat.

PAGE 99

91 Denition7.5:stack Apartofthecomputer'smemoryusedforstorageofdata. Denition7.6:scope Theareaofasourcecodelewhereanidentiernameisrecognized. 7.3UsingaHeaderFileforUserDenedSpecicTaskFunctions 3 7.3.1Concept:UserDenedSpecicTaskFunctions Mostcompanieshavecertaintasksthatareuniquetotheircompany.Collectivelytheprogrammingstamay decidetobuildseveralfunctionsandorganizethemintooneormoreuserlibraries.Specictaskfunctions areoftenbuiltusingatestingshellprogram.Thesolepurposeofthetestingshellprogramistocreate thespecictaskfunctionsandtotestthemtoinsurethattheyareworkingproperly.Thinkofaclam,its shellsurroundstheimportantpart,thepearl.Atestingshellprogramsurroundsthespecictaskfunction theimportantpart.Usuallythetestingshellprogramwillbeusedtocreateseveralfunctionsthatwillbe placedintoauserdenedlibrary.Theprocessowsasfollows: 1.The testingshell programwiththespecictaskfunctionsisbuiltandthoroughlytested. 2.Acopyofthesourcecodeissavedasthe headerle thatwillbeplacedintheuserlibrary.You deletethemainpartoftheprogramleavingacommentsarea,anyneededincludelereferencesand thespecictaskfunctions. 3.Acopyoftheheaderleissavedasthe prototypesle .Thisisatextlethatstripsoutthefunction code,addsasemicolontocreatetheprototypes.Thefunctionsshouldbeusingmeaningfulidentier names,thustheprototypesshouldprovideadequateinformationtoothersonhowtocallthefunction withappropriateparameterpassing. 4.Anothercopyofthesourcecodeissavedasa verifyheaderprogram .Youdeletethefunctionsand provideanincludethatpointstotheheaderle.Thisprogramiscompiledandruntomakesurethe headerleisworkingproperly. Agoodwaytounderstandtheconceptistoreviewthefourlesdescribedabovethathavebeencreatedby aprogrammer.WewillbeusingtheC++programminglanguage,howeverthecodeiseasytounderstand andwillserveourneedswellatexplainingtheconcepts;evenifyouarenotfamiliarwithC++. 7.3.2DemonstrationUsingC++ 7.3.2.1CreatingaFolderorSub-FolderfortheFourFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Monitor_Header Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 7.3.2.2DownloadtheFourFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolder.Youmayneedto rightclickonsomeofthelinksandselect"SaveTargetAs"inordertodownloadsomeoftheles. DownloadfromConnexions:Monitor_Testing_Shell.cpp 4 3 Thiscontentisavailableonlineat. 4 Seetheleat

PAGE 100

92 CHAPTER7.7.SPECIFICTASKFUNCTIONS DownloadfromConnexions:udst_monitor.h 5 DownloadfromConnexions:udst_monitor_prototypes.txt 6 DownloadfromConnexions:Monitor_Verify_Header.cpp 7 7.3.2.3StudytheFilesCollectivelytoUnderstandtheConcepts Takeafewmomentstoreviewthelesinconjunctionwiththeconceptdiscussionabove.Youshouldcompile andrunthe Monitor_Testing_Shell.cpp program. 7.3.2.4CreatingaFolderorSub-FolderforyourUserLibrary Dependingonyourcompiler/IDE,youshoulddecidewheretocreateafolderthatwillholdtheheader lesyoucreate.Wesuggestthatyoucreatethefolderinconjunctionwiththecompiler/IDEsoftware.If youwereusingthe BloodshedDev-C++5compiler/IDE youmostlikelyinstalledthecompiler/IDE softwareat: C: n Dev-Cpp n ifyouinstalleditonyourmachineorat: DriveLetter: n Dev-Cpp n wherethe DriveLetter isthedrivethatrepresentsyourashdriveifyouinstalleditonaashdrive.Wesuggest thatyoucreateasub-folderatthatlocationnamed: user_library Thepathof: C: n Dev-Cpp n user_library wouldbecreatedasthelocationforyouruserlibraryifusing yourmachineinstallation.Youcanliterallyplaceitanywhereandnamethelibraryanyname,butonceyou decideonaplaceandname;youdonotwanttomoveorrenamethefolders. 7.3.2.5PlacingtheHeaderFileintotheUserLibrary Youneedtocopythe udst_monitor.h leplacingitintotheuser_libraryfolderjustcreated.Asyoucan guesstheudststandsforuserdenedspecictask.Thefunctionswithinthisheaderlewouldbeused tocontroltheinteractionauserhaswiththemonitor.The.hisaconventionoftheC++programming languageandindicatesaheaderle.Thustheidentiernamefortheheaderleisverymeaningfuland descriptive. 7.3.2.6VerifythattheHeaderFileWorksProperly Reviewthe Monitor_Verify_Header.cpp sourcecodeleandnotethetwoincludecommandsaredifferent. 1.TheStandardLibraryusesalessthanandagreaterthantobrackettheStandardLibrarynameof: iostream 2.Theuserlibraryusesquotemarkstobracketthelocationoftheheaderle.Thisidentiestothe complierthatwearespecifyingtheexactlewewant.Weprovideacompletelespecicationdrive, pathinformation,lenameandextension. 3.BecausethisitemistechnicallyastringwithinC++,wemustusetwobackslashesbetweenthedrive, pathsandlename.Thisisbecausetherstbackslashassumesthatthenextcharacterisanescape codeandifwereallydon'twantanescapecodebutabackslash,thesecondbackslashsaysnoI wantedabackslash.Thisstring:"C: nn Dev-Cpp nn user_library nn udst_monitor.h"willbeinterpreted tomean: C: n Dev-Cpp n user_library n udst_monitor.h Dependingonwhatdriveyouareusing,whatpathfolderstructureyouareusingandwhatyoucalledyour folder;youmayneedtocorrecttheincludereferencewithinthesourcecodesothatitproperlyreferences theheaderle. 5 Seetheleat 6 Seetheleat 7 Seetheleat

PAGE 101

93 CompileandruntheMonitor_Verify_Header.cppprogram.Note:ItshouldworkexactlyastheMonitor_Testing_Shell.cppprogram. 7.3.3Denitions Denition7.7:udst UserDenedSpecicTask Denition7.8:testingshell Aprogramusedtocreatespecictaskfunctions. Denition7.9:headerle Alethatcontainsitemswewanttohaveincludedtowardthetopofoursourcecode. 7.4Practice7:SpecicTaskFunctions 8 7.4.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Givenatestingshellprogramalreadycodedandtested,createauserdenedspecictaskheaderle, auserdenedspecictaskprototypesdocumentandasourcecodeprogramtoverifythattheheader leworksproperly. 7.4.2MemoryBuildingActivities Linkto:MBA07 9 7.4.3Exercises Exercise7.1 Solutiononp.95. Answerthefollowingstatementsaseithertrueorfalse: 1.Scopereferstoabrandofmouthwash. 2.Userdenedspecictaskfunctionsareusuallyplacedintoauserdenedlibrary. 3.Localandglobaldatastorageisassociatedwiththeconceptofscope. 4.Creatingaheaderleforuserdenedspecictaskfunctionsisadiculttask. 5.Thestackispartofthecomputer'smemoryusedforstorageofdata. 7.4.4MiscellaneousItems Noneatthistime. 8 Thiscontentisavailableonlineat. 9 Seetheleat

PAGE 102

94 CHAPTER7.7.SPECIFICTASKFUNCTIONS 7.4.5LabAssignment 7.4.5.1CreatingaFolderorSub-FolderforChapter07Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_07withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 7.4.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_07_Testing_Shell.cpp 10 7.4.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. Navigatetoyoursub-folder:Chapter_07.CompileandruntheLab07TestingShellsourcecode.Note: Thisprogramusesanincludelethatpointstothe"udst_monitor.h"leasexplainedinConnexions Chapter7materials. FollowingsameprocessasshownintheConnexionsmodule"UsingaHeaderFilefor UserDenedSpecicTaskFunctions"thatiswithintheChapter7materials;make thefollowingles: udst_us_to_metric.h and udst_us_to_metric_prototypes.txt and Lab_07_Verify_Header.cpp Copytheheaderletoyouruserlibrary,thenbuildcompileandrunyourverifyheaderprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 7.4.6Problems 7.4.6.1Problem07aInstructions Createthepseudocodetosolvethefollowingspecictaskfunction: Problem:Aninteriordesigneralwaysneedstocalculatetheareaofaroomtodeterminetheamount ofoorcoveringneededusuallycarpet.Theroomsarerectangularwiththedimensionsmeasuredinfeet withdecimalfractions.Thefunctionhoweverneedstoreturnsquareyards.Hint:Thereare3linealfeet toayard. 7.4.6.2Problem07bInstructions Createtestdatathefollowingspecictaskfunction: Problem:Aninteriordesigneralwaysneedstocalculatetheareaofaroomtodeterminetheamount ofoorcoveringneededusuallycarpet.Theroomsarerectangularwiththedimensionsmeasuredinfeet withdecimalfractions.Thefunctionhoweverneedstoreturnsquareyards.Hint:Thereare3linealfeet toayard. 10 Seetheleat

PAGE 103

95 SolutionstoExercisesinChapter7 SolutiontoExercise7.1p.93 Answers: 1.falseAlthoughScopeisabrandofmouthwash;wearelookingforthecomputerrelateddenition. 2.true 3.true 4.falseItmayseemdicultatrst,butwithalittlepracticeitisreallyquiteeasy. 5.true

PAGE 104

96 CHAPTER7.7.SPECIFICTASKFUNCTIONS

PAGE 105

Chapter8 8.StandardLibraries 8.1StandardLibraries 1 8.1.1OverviewofStandardLibraries Manycommonor standardfunctions ,whosedenitionshavebeenwritten,arereadytobeusedinany program.Theyareorganizedintoagroupoffunctionsthinkofthemasseveralbooksandarecollectively calleda StandardLibrary TherearemanyfunctionorganizedintoseverallibrariesForexample,within C++manymathfunctionsexistandhavebeencodedandplacedintolibraries.Thesefunctionswere writtenbyprogrammersandtestedtoinsurethattheyworkproperly.Inmostcasesthefunctionswere reviewedbyseveralpeopletodoubleandtriplechecktoinsurethattheydidwhatwasexpected.Wehave theadvantageofusingthesefunctionswith condence thattheywillworkproperlyinourprograms,thus savingustimeandmoney. Amainprogrammustestablishtheexistenceoffunctionsusedinthatprogram.Dependingonthe programminglanguage,thereisaformalwayto: 1.deneafunction 2.declareafunctionaprototypeisadeclarationtoacompiler 3.callafunction Whenwecreatefunctionsinourprogram,weusuallyseetheminthefollowingorderinoursourcecode listing: 1.declarethefunctionprototype 2.callthefunction 3.denethefunction Whenweusefunctionscreatedbyothersthathavebeenorganizedintolibrary,weincludeaheaderlein ourprogramwhichcontainstheprototypesforthefunctions.Justlikefunctionsthatwecreate,weseethem inthefollowingorderinoursourcecodelisting: 1.declaringthefunctionprototypeprovidedintheincludele 2.callthefunctionwithparameterpassingofvalues 3.denethefunctionitiseitherdenedintheheaderleorthelinkerprogramprovidestheactual objectcodefromaStandardLibraryobjectarea 1 Thiscontentisavailableonlineat. 97

PAGE 106

98 CHAPTER8.8.STANDARDLIBRARIES Inmostcases,theusercanlookattheprototypeandunderstandexactlyhowthecommunicationsparameter passingintoandoutofthefunctionwilloccurwhenthefunctioniscalled.Let'slookatthemathexample ofabsolutevalue.Theprototypeis: intabsintnumber; Notwantingtohavealongfunctionnamethedesignersnamedit: abs insteadof"absolute".Thismight seemtoviolatetheidentiernamingruleofusingmeaningfulnames,howeverwhenidentiernamesare establishedforstandardlibrariestheyareoftenshortenedtoanamethatiseasilyunderstoodbyallwho wouldbeusingthem.Thefunctionisofdatatypeint,meaningthatthefunctionwillreturnaninteger value.Itisobviousthattheintegervaluereturnedistheanswertothequestion,"Whatistheabsolute valueoftheintegerthatisbeingpassedintothefunction".Thisfunctionispassedonlyonevalue;anint number.IfIhadtwointegervariablesnamedappleandbanana;andIwantedtostoretheabsolutevalueof bananaintoapple;thenalineofcodetocallthisfunctionwouldbe: apple=absbanana; Let'ssayitinEnglish,passthefunctionabsolutethevaluestoredinvariablebananaandassignthe returningvaluefromthefunctiontothevariableapple.Thus,ifyouknowtheprototypeyoucanusually properlycallthefunctionanduseitsreturningvalueifithasonewithouteverseeingthedenitionofthe codei.e.thesourcecodethattellsthefunctionhowtogettheanswer;thatiswrittenbysomeoneelse; andeitherincludedintheheaderleorcompiledandplacedintoanobjectlibrary;andlinkedduringthe linkingstepoftheIntegratedDevelopmentEnvironmentIDE. 8.1.2DemonstrationPrograminC++ 8.1.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 8.1.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneedto rightclickonsomeofthelinksandselect"SaveTargetAs"inordertodownloadsomeoftheles.Following themethodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodeand/orother lesinconjunctionwithotherlearningmaterials. DownloadfromConnexions:Demo_Standard_Libraries.cpp 2 DownloadfromConnexions:Demo_Standard_Libraries_Listing.txt 3 8.1.3Denitions Denition8.1:StandardLibrary Asetofspecictaskfunctionsthathavebeenaddedtotheprogramminglanguageforuniversal use. Denition8.2:condence ThereliancethatStandardLibraryfunctionsworkproperly. Denition8.3:abs AfunctionwithinthecmathstandardlibraryinC++whichstandsforabsolute. 2 Seetheleat 3 Seetheleat

PAGE 107

99 8.2Practice8:StandardLibraries 4 8.2.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Givenatestingshellprogramalreadycodedandtested,addanotherspecictaskfunction,andtest it,thencreateauserdenedspecictaskheaderle,auserdenedspecictaskprototypesdocument andasourcecodeprogramtoverifythattheheaderleworksproperly. 8.2.2MemoryBuildingActivities Linkto:MBA08 5 8.2.3Exercises Exercise8.1 Solutiononp.101. Answerthefollowingstatementsaseithertrueorfalse: 1.Thestandardlibraryisasetofspecictaskfunctionsthathavebeenaddedtotheprogramminglanguageforuniversaluse. 2.Programmersshouldnothavecondencethatstandardlibraryfunctionsworkproperly. 3.Itwouldbeeasiertowriteprogramswithoutusingspecictaskfunctions. 8.2.4MiscellaneousItems Noneatthistime. 8.2.5LabAssignment 8.2.5.1CreatingaFolderorSub-FolderforChapter08Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_08withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 8.2.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_08_Testing_Shell.cpp 6 4 Thiscontentisavailableonlineat. 5 Seetheleat 6 Seetheleat

PAGE 108

100 CHAPTER8.8.STANDARDLIBRARIES 8.2.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. Navigatetoyoursub-folder:Chapter_08.CompileandruntheLab08TestingShellsourcecode.Note: Thisprogramusesanincludelethatpointstothe"udst_monitor.h"leasexplainedinConnexions Chapter7materials. Youneedtoaddanotherfunctiontothistestingshelltitled:area_trianglethatistocalculatethearea ofatriangle.Denethefunction,prototypeit,andwithinthefunctionmainaddanareaforcalling thefunctionsimilartotheexistingfunctionswithtestdata.Becondentthatitisworkingproperly. FollowingsameprocessasshownintheConnexionsmodule"UsingaHeaderFileforUserDenedSpecicTaskFunctions"thatiswithintheChapter7materials;makethefollowingles: udst_geo_area.h and udst_geo_area_prototypes.txt and Lab_08_Verify_Header.cpp Copytheheaderletoyouruserlibrary,thenbuildcompileandrunyourverifyheaderprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 8.2.6Problems 8.2.6.1Problem08aInstructions WritetheC++codetodothefollowingspecictaskfunction. Example8.1:pseudocode Functionarea_regular_hexagon PassIn:side Calculate:sidetimessidetimes3timesthesquarerootof0.75 PassOut:thecalculation Endfunction

PAGE 109

101 SolutionstoExercisesinChapter8 SolutiontoExercise8.1p.99 Answers: 1.true 2.false 3.false

PAGE 110

102 CHAPTER8.8.STANDARDLIBRARIES

PAGE 111

Chapter9 9.CharacterData,Sizeof,Typedef, Sequence 9.1CharacterDataType 1 9.1.1OverviewoftheCharacterDataType The character datatypebasicallyrepresentsindividualorsinglecharacters.Characterscompriseavariety ofsymbolssuchasthealphabetbothupperandlowercasethenumeraldigitsto9,punctuation,etc. Allcomputersstorecharacterdatainaonebyteeldasanintegervalue.Becauseabyteconsistsof8bits, thisonebyteeldhas28or256possibilitiesusingthepositivevaluesof0to255. Mostmicrocomputersusethe ASCII standsforAmericanStandardCodeforInformationInterchange andispronounced"ask-key"CharacterSetwhichhasestablishedvaluesfor0to127.Forthevaluesof128 to255theyusuallyusetheExtendedASCIICharacterSet.WhenwehitthecapitalAonthekeyboard,the keyboardsendsabytewiththebitpatternequaltoaninteger65.Whenthebyteissentfromthememory tothemonitor,themonitorconvertstheintegervalueof65tointothesymbolofthecapitalAtodisplay onthemonitor. Thecharacterdatatypeattributesinclude: C++ReservedWord char Represent Singlecharacters Size 1byte NormalSignage Unsignedpositivevaluesonly DomainValuesAllowed Valuesfrom0to127asshowninthestandard ASCIICharacterSet,plusvalues128to255from theExtendedASCIICharacterSet continuedonnextpage 1 Thiscontentisavailableonlineat. 103

PAGE 112

104 CHAPTER9.9.CHARACTERDATA,SIZEOF,TYPEDEF,SEQUENCE C++syntaxrule SinglequotemarksExample:'A' Table9.1 9.1.2DemonstrationPrograminC++ 9.1.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 9.1.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesorucecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Character_Data_Type.cpp 2 9.1.3Denitions Denition9.1:character Adatatyperepresentingsingletextcharacterslikethealphabet,numeraldigits,punctuation,etc. Denition9.2:ASCII AmericanStandardCodeforInformationInterchange Denition9.3:singlequotemarks UsedtocreatecharactertypedatawithintheC++programminglanguage. 9.2SizeofOperator 3 9.2.1Overview Everydataitem,constantsandvariables,notonlyhaveadatatype,butthedatatypedetermineshowmany bytestheitemwilluseinthememoryofthecomputer.Thesizeofeachdatatypevarieswiththecomplier beingusedandthecomputer.Thiseectisknownasbeing machinedependent .Additionally,therehave beensomesizechangeswithupgradestothelanguage.In"C"theintdatatypewasallocated2bytesof memorystorageonanIntelcompatiblecentralprocessingunitcpumachine.In"C++"anintisallocated 4bytes. Thereisanoperatornamed"sizeof ::: "thatisaunaryoperator,thatisithasonlyoneoperand.The operandistotherightoftheoperatorandisplacedwithintheparenthesesifitisadatatype.Theoperand maybeanydatatypeincludingthosecreatedbytypedef.Ifanidentiernameitdoesnotneedtogo insideoftheparentheses.Itworksforbothvariableandmemoryconstantidentiernames.Thisoperator isuniqueinthatitdoesitscalculationatcompiletimeforglobalscopeditemsandatruntimeforlocal scopeditems.Examples: 2 Seetheleat 3 Thiscontentisavailableonlineat.

PAGE 113

105 cout "Thesizeofanintegeris:" sizeofint; Thecompilerwoulddeterminethebytesizeofanintegeronthespecicmachineandinessencereplaces thesizeofoperatorwithavalue.Integersareusually4byteslong,thusthelineofcodewouldbechanged to: cout "Thesizeofanintegeris:" 4; Ifyouplaceanidentiernamethatrepresentsadatastorageareavariableormemoryconstant,itlooks atthedenitionfortheidentiername.NOTE:theparenthesesarenotneededandoftennotincludedfor anidentiername. Example9.1:sizeofwithaVariable doublemoney;//variablesetupwithinitialization thenlateronintheprogram cout "Thesizeofmoneyis:" sizeofmoney; Thecompilerwoulddeterminethebytesizeofmoneybylookingatthedenitionwhereitindicatesthat thedatatypeisdouble.Thedoubledatatypeonthespecicmachineusually8byteswouldreplacethe codeanditwouldbecome: cout "Thesizeofmoneyis:" 8; 9.2.2Denitions Denition9.4:sizeof Anoperatorthattellsyouhowmanybytesadatatypeoccupiesinstorage. 9.3Typedef-AnAlias 4 9.3.1GeneralDiscussion Thetypedefstatementallowstheprogrammertocreateanalias,orsynonym,foranexistingdatatype. Thiscanbeusefulindocumentingaprogram.TheC++programminglanguagesyntaxis: typedef < therealdatatype >< thealiasidentifiername > ; Let'ssayaprogrammerisusingadoubledatatypetostoretheamountofmoneythatisbeingusedfor variouspurposesinaprogram.Hemightdenethevariablesasfollows: Example9.2:RegularDenitionofVariables doubleincome; doublerent; doublevacation; However,hemightusethetypedefstatementanddenethevariablesasfollows: Example9.3:UsingtypedefwhenDeningVariables 4 Thiscontentisavailableonlineat.

PAGE 114

106 CHAPTER9.9.CHARACTERDATA,SIZEOF,TYPEDEF,SEQUENCE typedefdoublecash; thetypedefmustbedefinedbeforeitsuse cashincome; cashrent; cashvacation; Thetypedefstatementisnotusedveryoftenbybeginningprogrammers.Itusuallycreatesmoreconfusion thanneeded,thussticktousingthenormaldatatypesatrst. 9.3.2Denitions Denition9.5:typedef Allowstheprogrammertocreateanalias,orsynonym,foranexistingdatatype. 9.4SequenceOperator 5 9.4.1GeneralDiscussion The sequence orcommaoperatorisusedtoseparateitems.Ithasseveraluses,fourofwhicharelisted thendemonstrated: 1.Toseparateidentiernameswhendeclaringvariablesorconstants 2.Toseparateseveralparametersbeingpassedintoafunction 3.Toseparateseveralinitializationitemsorupdateitemsinaforloop 4.Separatevaluesduringtheinititalizationofanarray Thisrstexampleisoftenseenintextbooks,butthismethodofdeclaringvariablesisnotpreferred.Itis diculttoquicklyreadtheidentiernames. intpig,dog,cat,rat; Thefollowingverticalmethodofdeclaringvariablesorconstantsispreferred. Example9.4:PreferredVerticalMethodofDeningVariables intpig; intdog; intcat; intrat; Thedatatypesandidentiernamesknownasparametersareseparatedfromeachother.Thisexampleis afunctionprototype. doublearea_trapezoiddoublebase,doubleheight,doubletop; Inthesyntaxofaforloopyouhavethreepartseachseparatedbyasemi-colon.Therstistheinitializationareawhichcouldhavemorethanoneinitialization.Thelastistheupdateareawhichcouldhave morethanoneupdate.Mutipleinitializationsorupdatesusethecommatoseparatethem.Thisexampleis onlytherstlineofaforloop. forx=1,y=5;x < 15;x++,y++ Thevariableagesisanarrayofintegers.Initialvaluesareassignedusingblockmarkerswiththevalues separatedfromeachotherusingacomma. intages[]={2,4,6,29,32}; 5 Thiscontentisavailableonlineat.

PAGE 115

107 9.4.2Denitions Denition9.6:sequence Anoperatorusedtoseparatemultipleoccurrencesofanitem. 9.5Practice9:CharacterData,Sizeof,Typedef,Sequence 6 9.5.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.GivenappropriatedocumentsproducedbyaSystemAnalyst,createplanningdocumentspseudocode andtestdata,thenasourcecodeprogramthataccomplishesthegoalsoftheprogram. 9.5.2MemoryBuildingActivities Linkto:MBA09 7 9.5.3Exercises Exercise9.1 Solutiononp.109. Answerthefollowingstatementsaseithertrueorfalse: 1.ThecharacterdatatypeinC++usesthedoublequotemarks,like:chargrade="A"; 2.Sizeofisanoperatorthattellsyouhowmanybytesadatatypeoccupiesinstorage. 3.Typedefhelpspeoplewhocan'thearandisoneofthestandardaccommodationfeaturesofa programminglanguageforpeoplewithalearningdisability. 4.Thesequenceoperatorshouldbeusedwhendeningvariablesinordertosavespace. 5.Programmingcanbebothenjoyableandfrustrating. 9.5.4MiscellaneousItems Noneatthistime. 9.5.5LabAssignment 9.5.5.1CreatingaFolderorSub-FolderforChapter09Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_09withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 6 Thiscontentisavailableonlineat. 7 Seetheleat

PAGE 116

108 CHAPTER9.9.CHARACTERDATA,SIZEOF,TYPEDEF,SEQUENCE 9.5.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_09_Narrative_Description.txt 8 DownloadfromConnexions:Lab_09_Aerial_View_Center_Pivot_Irrigation.jpg 9 DownloadfromConnexions:Lab_09_Hierarchy_Chart.jpg 10 9.5.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. ReviewtheConnexionsmodule"SystemsDevelopmentLifeCycle"withintheChapter1materials. ThinkofyourselfasaprogrammerassignedtoaprojectduringtheImplementationphasewithyour professorastheSystemAnalyst. Navigatetoyoursub-folder:Chapter_09.Reviewthersttwoitemsprovidedbythesystemanalyst whichheproducedduringtheDesignphaseoftheSystemsDevelopmentLifeCycle.Thesetwo documentshistoricallywouldhavebeenprintedandbeplacedintoaprogramdocumentationfolder. Theitemsyouproduceincreatingtheprogramwouldbeaddedtothefolder.However,shiftingtoour paperlessviewoftheworld,todaytheseitemsmightbecreatedandstoredelectronicallyinelectronic folderswhichisbasicallywhatwearedoingbyusingoursub-foldertitled:Chapter_09.Thethird item,thehierarchychart,wouldnormallybeproducedbytheprogrammer.However,givenyour inexperience,thesystemanalysthascreateditforyou.Makesureyouunderstandwhattheprogram istodo.Anyquestionsaskthesystemanalystakayourprofessor. Designtheprogramandcreateyourtestdatabybuildinga Lab_09_Pseudocode.txt leanda Lab_09_Test_Data.txt le.WARNING:Don'ttouchthecompiler/IDE.Don'tstartbycreating thesourcecodele.Creatingthesourcecodethenproducingtheplanningdocumentationafterwards isabadhabitthatbeginningprogrammersoftenacquire.NOTE:Inyourpseudocodedocument youdonotneedtocreateanypseudocodefortheStandardLibraryorUserLibraryfunctions.Just indicatethatyoucallthemfromtheProgramControlfunctions.Ifneeded,reviewtheConnexions module"PseudocodeExamplesforFunctions"withintheChapter6materials.HINT:Copyingthe pseudocodeandtestdatalesfromtheChapter06foldermightbeagoodwaytostartbuildingthese items. Afteryouhavesuccessfullyplannedthedocumentandcreatedyourtestdata;createthesourcecode lenamingit: Lab_09.cpp HINTS:Usingaprevioussourcecodeleasyourstartinglemakes sense.TheleintheChapter06foldermightbeagoodstart.Youmightwanttocopysomeofthe includeinformationfromtheVerifyHeadercodeinChapter08intoyourLab09sourcecodele. Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 9.5.6Problems 9.5.6.1Problem09aInstructions Thesequenceoperatorcanbeusedwhendeclaringmultipleidentiernamesforvariablesorconstantsofthe samedatatype.Isthisagoodorbadprogramminghabitandwhy? 8 Seetheleat 9 Seetheleat 10 Seetheleat

PAGE 117

109 SolutionstoExercisesinChapter9 SolutiontoExercise9.1p.107 Answers: 1.false 2.true 3.false 4.false 5.true

PAGE 118

110 CHAPTER9.9.CHARACTERDATA,SIZEOF,TYPEDEF,SEQUENCE

PAGE 119

Chapter10 10.IntroductiontoStructured Programming 10.1StructuredProgramming 1 10.1.1Introduction Oneofthemostimportantconceptsofprogrammingistheabilitytocontrolaprogramsothatdierent linesofcodeareexecutedorthatsomelinesofcodeareexecutedmanytimes.Themechanismsthatallow ustocontroltheowofexecutionarecalled controlstructures .Flowchartingisamethodofdocumenting chartingtheoworpathsthataprogramwouldexecute.Therearefourmaincategoriesofcontrol structures: Sequence Veryboring.Simplydooneinstructionthenthenextandthenext.Justdothemina givensequenceorinorderlisted.Mostlinesofcodearethis. Selection Thisiswhereyouselectorchoosebetweentwoormoreows.Thechoiceisdecidedby askingsomesortofquestion.Theanswerdeterminesthepathorwhichlinesofcodewillbeexecuted. Iteration Alsoknownasrepetition,itallowssomecodeonetoomanylinestobeexecutedor repeatedseveraltimes.Thecodemightnotbeexecutedatallrepeatitzerotimes,executedaxed numberoftimesorexecutedindenitelyuntilsomeconditionhasbeenmet.Alsoknownaslooping becausetheowchartingshowstheowloopingbacktorepeatthetask. Branching Acontrolstructurethatallowstheowofexecutiontojumptoadierentpartofthe program.Thiscategoryisrarelyusedinmodularstructuredprogramming. Allhigh-levelprogramminglanguageshavecontrolstructures.Alllanguageshavetherstthreecategoriesof controlstructuressequence,selection,anditeration.Mosthavethe ifthenelse structurewhichbelongs totheselectioncategoryandthe while structurewhichbelongstotheiterationcategory.Afterthese twobasicstructuresthereareusuallylanguagevariations. Theconceptof structuredprogramming startedinthelate1960'swithanarticlebyEdsgerDijkstra. Heproposeda"gotoless"methodofplanningprogramminglogicthateliminatedtheneedforthebranching categoryofcontrolstructures.Thetopicwasdebatedforabout20years.Butultimately"Bytheend ofthe20thcenturynearlyallcomputerscientistswereconvincedthatitisusefultolearnandapplythe conceptsofstructuredprogramming." 2 1 Thiscontentisavailableonlineat. 2 StructuredprogrammingfromWikipedia 111

PAGE 120

112 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING 10.1.1.1IntroductiontoSelectionControlStructures Thebasicattributeofaselectioncontrolstructureistobeabletoselectbetweentwoofmorealternate paths.Thisisdescribedaseither two-wayselection or multiwayselection .AquestionusingBoolean conceptsusuallycontrolswhichpathisselected.Allofthepathsfromaselectioncontrolstructurejoinback upattheendofthecontrolstructure,beforemovingontothenextlinesofcodeinaprogram. Wehavementionedthatthe ifthenelse controlstructurebelongstotheselectioncategoryandisa two-wayselection. Example10.1:ifthenelsecontrolstructure ifage > 17 { out "Youcanvote."; } else { cout "Youcan'tvote."; } 10.1.1.2IntroductiontoIterationControlStructures Thebasicattributeofaniterationcontrolstructureistobeabletorepeatsomelinesofcode.Thevisual displayofiterationcreatesacircularlooppatternwhenowcharted,thustheword"loop"isassociatedwith iterationcontrolstructures.Iterationcanbeaccomplishedwith testbeforeloops countingloops ,and testafterloops .AquestionusingBooleanconceptsusuallycontrolshowlongtheloopwillexecute. Wehavementionedthatthe while controlstructurebelongstotheiterationcategoryandisatestbefore loop. Example10.2:whilecontrolstructure counter=0; whilecounter < 5 { cout n nIlovecomputers!"; counter++; } 10.1.2Denitions Denition10.1:controlstructures Mechanismsthatallowustocontroltheowofexecutionwithinaprogram. Denition10.2:sequence Acontrolstructurewhereyoudotheitemsinthesequencelisted.

PAGE 121

113 Denition10.3:selection Acontrolstructurewhereyouselectbetweentwoormorechoices. Denition10.4:iteration Acontrolstructurethatallowssomelinesofcodetobeexecutedmanytimes. Denition10.5:branching Acontrolstructurethatallowstheowofexecutiontojumptoadierentpartoftheprogram. Denition10.6:structuredprogramming Amethodofplanningprogramsthatavoidsthebranchingcategoryofcontrolstructures. 10.2PseudocodeExamplesforControlStructures 3 10.2.1Overview Nostandardforpseudocodesyntaxexists.However,therearesomecommonlyfollowedconventionstohelp makepseudocodewrittenbyoneprogrammereasilyunderstoodbyanotherprogrammer.Mostofthese conventionsfollowtwoconcepts: Useindentationtoshowtheactionpartofacontrolstructure Useanending phraseword toendacontrolstructure Thesequencecontrolstructuresimplyliststhelinesofpseudocode.Theconcernisnotwiththesequence categorybutwithselectionandtwooftheiterationcontrolstructures.Thefollowingarecommonlyused endingphrase-words: ControlStructure EndingPhraseWord IfthenElse Endif Case Endcase While Endwhile For Endfor Table10.1 The DoWhile and RepeatUntil iterationcontrolstructuresdon'tneedanendingphrase-word.We simplyusetherstword,thentheactionpart,followedbythesecondwordwiththetestexpression.Here aresomeexamples: 10.2.2SelectionControlStructures Example10.3:pseudocode:IfthenElse Ifage > 17 Displayamessageindicatingyoucanvote. Else Displayamessageindicatingyoucan'tvote. Endif 3 Thiscontentisavailableonlineat.

PAGE 122

114 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING Example10.4:pseudocode:Case Caseofage 0to17Display"Youcan'tvote." 18to64Display"Yourinyourworkingyears." 65+Display"Youshouldberetired." Endcase 10.2.3IterationRepetitionControlStructures Example10.5:pseudocode:While countassignedzero Whilecount < 5 Display"Ilovecomputers!" Incrementcount Endwhile Example10.6:pseudocode:For Forxstartsat0,x < 5,incrementx Display"Arewehavingfun?" Endfor Example10.7:pseudocode:DoWhile countassignedfive Do Display"Blastoffissoon!" Decrementcount Whilecount > zero Example10.8:pseudocode:RepeatUntil countassignedfive Repeat Display"Blastoffissoon!" Decrementcount Untilcount < one

PAGE 123

115 10.3Flowcharting 4 10.3.1FlowchartingSymbols 10.3.1.1Terminal Theroundedrectangles,orterminalpoints,indicatetheowchart'sstartingandendingpoints. Figure10.1 10.3.1.2Process Therectangledepictsaprocesssuchasamathematicalcomputation,oravariableassignment. Note:theC++languageequivalentisthestatement. 4 Thiscontentisavailableonlineat.

PAGE 124

116 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING Figure10.2 10.3.1.3Input/Output Theparallelogramsdesignateinputoroutputoperations. Note:theC++languageequivalentiscinorcout. Figure10.3 10.3.1.4Connectors Sometimesaowchartisbrokenintotwoormoresmallerowcharts.Thisisusuallydonewhenaowchart doesnottonasinglepage,ormustbedividedintosections.Aconnectorsymbol,whichisasmallcircle

PAGE 125

117 withaletterornumberinsideit,allowsyoutoconnecttwoowchartsonthesamepage.Aconnectorsymbol thatlookslikeapocketonashirt,allowsyoutoconnecttoaowchartonadierentpage. On-PageConnector Figure10.4 O-PageConnector Figure10.5 10.3.1.5Decision Thediamondisusedtorepresentthetrue/falsestatementbeingtestedinadecisionsymbol.

PAGE 126

118 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING Figure10.6 10.3.1.6ModuleCall Aprogrammoduleisrepresentedinaowchartbyrectanglewithsomelinestodistinguishitfromprocess symbol.Oftenprogrammerswillmakeadistinctionbetweenprogramcontrolandspecictaskmodulesas shownbelow. Note:C++equivalentisthefunction. Localmodule:usuallyaprogramcontrolfunction. Figure10.7 Librarymodule:usuallyaspecictaskfunction.

PAGE 127

119 Figure10.8 10.3.1.7FlowLines Note:ThedefaultowislefttorightandtoptobottomthesamewayyoureadEnglish.Tosavetime arrowheadsareoftenonlydrawnwhentheowlinesgocontrarythenormal. Figure10.9 10.3.2Examples Wewilldemonstratevariousowchartingitemsbyshowingtheowchartforsomepseudocode.

PAGE 128

120 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING 10.3.2.1Functions Example10.9:pseudocode:Functionwithnoparameterpassing Functionclearmonitor PassIn:nothing Directtheoperatingsystemtoclearthemonitor PassOut:nothing Endfunction Figure10.10: Functionclearmonitor Example10.10:pseudocode:Functionmaincallingtheclearmonitorfunction Functionmain PassIn:nothing Doingsomelinesofcode Call:clearmonitor Doingsomelinesofcode PassOut:valuezerototheoperatingsystem Endfunction

PAGE 129

121 Figure10.11: Functionmain 10.3.2.2SequenceControlStructures Thenextitemispseudocodeforasimpletemperatureconversionprogram.Thisdemonstratestheuseof boththeon-pageando-pageconnectors.Italsoillustratesthesequencecontrolstructurewherenothing unusuallyhappens.Justdooneinstructionafteranotherinthesequencelisted. Example10.11:pseudocode:Sequencecontrolstructure Filename:Solution_Lab_04_Pseudocode.txt Purpose:ConvertTemperaturefromFahrenheittoCelsius Author:KenBusbee; 2008KennethLeroyBusbee Date:Dec24,2008 Pseudocode=IPOOutline input displayamessageaskinguserforthetemperatureinFahrenheit getthetemperaturefromthekeyboard processing calculatetheCelsiusbyaddingsubtracting32fromtheFahrenheit temperaturethenmultiplytheresultby5then dividetheresultby9.Roundupordowntothewholenumber. HINT:Use32.0whensubtractingtoensurefloating-pointaccuracy. output displaythecelsiuswithanappropriatemessage

PAGE 130

122 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING pausesotheusercanseetheanswer Figure10.12: Sequencecontrolstructure

PAGE 131

123 Figure10.13: Sequencecontrolstructuredcontinued 10.3.2.3SelectionControlStructures Example10.12:pseudocode:IfthenElse Ifage > 17 Displayamessageindicatingyoucanvote. Else Displayamessageindicatingyoucan'tvote. Endif

PAGE 132

124 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING Figure10.14: IfthenElsecontrolstructure Example10.13:pseudocode:Case Caseofage 0to17Display"Youcan'tvote." 18to64Display"Yourinyourworkingyears." 65+Display"Youshouldberetired." Endcase

PAGE 133

125 Figure10.15: Casecontrolstructure 10.3.2.4IterationRepetitionControlStructures Example10.14:pseudocode:While countassignedzero Whilecount < 5 Display"Ilovecomputers!" Incrementcount Endwhile

PAGE 134

126 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING Figure10.16: Whilecontrolstructure Example10.15:pseudocode:For Forxstartsat0,x < 5,incrementx Display"Arewehavingfun?" Endfor Theforloopdoesnothaveastandardowchartingmethodandyouwillnditdoneindierentways.The forloopasacountingloopcanbeowchartedsimilartothewhileloopasacountingloop.

PAGE 135

127 Figure10.17: Forcontrolstructure Example10.16:pseudocode:DoWhile countassignedfive Do Display"Blastoffissoon!" Decrementcount Whilecount > zero

PAGE 136

128 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING Figure10.18: DoWhilecontrolstructure Example10.17:pseudocode:RepeatUntil countassignedfive Repeat Display"Blastoffissoon!" Decrementcount Untilcount < one

PAGE 137

129 Figure10.19: RepeatUntilcontrolstructure 10.3.3Denitions Denition10.7:owcharting Aprogrammingdesigntoolthatusesgraphicalelementstovisuallydepicttheowoflogicwithin afunction. Denition10.8:processsymbol Arectangleusedinowchartingfornormalprocessessuchasassignment. Denition10.9:input/outputsymbol Aparallelogramusedinowchartingforinput/outputinteractions. Denition10.10:decisionsymbol Adiamondusedinowchartingforaskingaquestionandmakingadecision. Denition10.11:owlines Linessometimeswitharrowsthatconnectthevariousowchartingsymbols. 10.4Practice10:IntroductiontoStructuredProgramming 5 10.4.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Givenpseudocode,writetheC++codeforaprogramthatusesifthenelseandwhilecontrolstructures. 5 Thiscontentisavailableonlineat.

PAGE 138

130 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING 10.4.2MemoryBuildingActivities Linkto:MBA10 6 10.4.3Exercises Exercise10.1 Solutiononp.131. Answerthefollowingstatementsaseithertrueorfalse: 1.Thereareonlytwocategoriesofcontrolstructures. 2.Branchingcontrolstructuresarerarelyusedingoodstructuredprogramming. 3.Ifthenelseisamultiwayselectioncontrolstructure. 4.Thewhilecontrolstructureispartofthebranchingcategory. 5.Pseudocodeisbetterthanowcharting. 10.4.4MiscellaneousItems Noneatthistime. 10.4.5LabAssignment 10.4.5.1CreatingaFolderorSub-FolderforChapter10Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_10withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 10.4.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_10_Pseudocode.txt 7 10.4.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefromtheLab_10_Pseudocode.txtle.Nameit:Lab_10.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 10.4.6Problems 10.4.6.1Problem10aInstructions Listthefourcategoriesofcontrolstructuresandprovideabriefdescriptionofeachcategory. 6 Seetheleat 7 Seetheleat

PAGE 139

131 SolutionstoExercisesinChapter10 SolutiontoExercise10.1p.130 Answers: 1.false 2.true 3.false 4.false 5.false

PAGE 140

132 CHAPTER10.10.INTRODUCTIONTOSTRUCTUREDPROGRAMMING

PAGE 141

Chapter11 11.TwoWaySelection 11.1IfThenElse 1 11.1.1IntroductiontoTwoWaySelection 11.1.1.1TraditionalTwoWaySelection Wearegoingtointroducethecontrolstructurefromtheselectioncategorythatisavailableineveryhigh levellanguage.Itiscalledthe ifthenelse structure.Askingaquestionthathasatrueorfalseanswer controlstheifthenelsestructure.Itlookslikethis: iftheanswertothequestionistrue thendothis elsebecauseit'sfalse dothis Inmostlanguagesthequestioncalleda testexpression isa Booleanexpression .TheBooleandata typehastwovaluestrueandfalse.Let'srewritethestructuretoconsiderthis: ifexpressionistrue thendothis elsebecauseit'sfales dothis Somelanguagesusereservedwordsof:"if","then"and"else".Manyeliminatethe"then".Additionally the"dothis"canbetiedtotrueandfalse.Youmightseeitas: ifexpressionistrue actiontrue else actionfalse Andmostlanguagesinferthe"istrue"youmightseeitas: 1 Thiscontentisavailableonlineat. 133

PAGE 142

134 CHAPTER11.11.TWOWAYSELECTION ifexpression actiontrue else actionfalse Theabovefourformsofthecontrolstructurearesayingthesamething.Theelsewordisoftennotused inourEnglishspeakingtoday.However,considerthefollowingconversationbetweenamotherandherchild. Childasks,"Mommy,mayIgooutsideandplay?" Motheranswers,"Ifyourroomiscleanthenyoumaygooutsideandplayorelseyoumaygositona chairforveminutesaspunishmentforaskingmethequestionwhenyouknewyourroomwasdirty." Let'snotethatalloftheelementsarepresenttodeterminetheactionorowthatthechildwillbe doing.Becausethequestionyourroomiscleanhasonlytwopossibleanswerstrueorfalsetheactions are mutuallyexclusive .Eitherthechild1goesoutsideandplaysor2sitsonachairforveminutes. Oneoftheactionsisexecuted;neverbothoftheactions. 11.1.1.2OneChoiceImpliedTwoWaySelection Oftentheprogrammerwillwanttodosomethingonlyiftheexpressionistrue,thatiswithnofalseaction. Thelackofafalseactionisalsoreferredtoasa"nullelse"andwouldbewrittenas: ifexpression actiontrue else donothing Becausethe"elsedonothing"isimplied,itisusuallywritteninshortformlike: ifexpression actiontrue 11.1.2TwoWaySelectionwithinC++ ThesyntaxfortheifthenelsecontrolstructurewithintheC++programminglanguageis: ifexpression statement; else statement; Note:Thetestexpressioniswithintheparentheses,butthisisnotafunctioncall.Theparentheses arepartofthecontrolstructure.Additionally,thereisnosemicolonaftertheparenthesisfollowingthe expression. 11.1.3Denitions Denition11.1:ifthenelse Atwowayselectioncontrolstructure. Denition11.2:mutuallyexclusive Itemsthatdonotoverlap.Example:trueandfalse.

PAGE 143

135 11.2BooleanDataType 2 11.2.1Discussion The Boolean datatypeisalsoknownasthelogicaldatatypeandrepresentstheconceptsoftrueandfalse. Thename"Boolean"comesfromthemathematicianGeorgeBoole;whoin1854published:AnInvestigation oftheLawsofThought.Booleanalgebraistheareaofmathematicsthatdealswiththelogicalrepresentation oftrueandfalseusingthenumbers0and1.TheimportanceoftheBooleandatatypewithinprogrammingis thatitisusedtocontrolprogrammingstructuresifthenelse,whileloops,etc.thatallowustoimplement "choice"intoouralgorithms. TheBooleandatatypehasthesameattributesandactsorbehavessimilarlyinallprogramminglanguages.TheruleswithintheC++programminglanguageare: C++ReservedWord bool Represent Logicalconceptsoftrueandfalse Size Usually1byte NormalSignage Unsigned DomainValuesAllowed 0meaningfalse,and1meaningtrue C++syntaxrule trueandfalsearereservedwordsthatcanbeused asvaluesinexpressions C++concept/rule Anyvaluefromanydatatypecanbedemotedinto aBooleandatatypewithzerorepresentingfalse andallnon-zerovaluesrepresentingtrue. Table11.1 Mostcontrolstructuresusea testexpression thatexecuteseitherselectionasinthe:ifthenelseor iterationasinthewhile;dowhile;orforloopsbasedonthetruthfulnessorfalsenessoftheexpression.Thus, weoftentalkaboutthe Booleanexpression thatiscontrollingthestructure.Withinmanyprogramming languages,thisexpressionmustbeaBooleanexpressionandisgovernedbyatightsetofrules.However,in C++everydatatypecanbeusedasaBooleanexpressionbecausethevalueofanydatatypewithinC++ canbedemotedintoaBooleanvalue. Withinmostlanguages,expressionsthatyieldBooleandatatypevaluesaredividedintotwogroups. Onegroupusestherelationaloperatorswithintheirexpressionsandtheothergroupuseslogicaloperators withintheirexpressions. WithintheC++programminglanguagetheBooleandatatypeisoneofthestandardorbasicdatatypes andisamemberoftheintegerfamily. 11.2.2Denitions Denition11.3:Boolean Adatatyperepresentingtheconceptsoftrueandfalse. Denition11.4:testexpression Anexpressionusedtocontrolprogrammingstructures. 2 Thiscontentisavailableonlineat.

PAGE 144

136 CHAPTER11.11.TWOWAYSELECTION 11.3RelationalOperators 3 11.3.1OverviewoftheRelationalOperators Therelationaloperatorsareoftenusedtocreatea testexpression thatcontrolsprogramow.Thistype ofexpressionisalsoknownasa Booleanexpression becausetheycreateaBooleananswerorvaluewhen evaluated.TherearesixcommonrelationaloperatorsthatgiveaBooleanvaluebycomparingshowingthe relationshipbetweentwooperands.Iftheoperandsareofdierentdatatypes,implicitpromotionoccurs toconverttheoperandstothesamedatatype. Denition11.5:relationaloperator AnoperatorthatgivesaBooleanvaluebyevaluatingtherelationshipbetweentwooperands. Operatorsymbolsand/ornamesvarywithdierentprogramminglanguages.TheC++programming languageoperatorswiththeirmeaningsare: C++Operator Meaning < lessthan > greaterthan < = lessthanorequalto > = greaterthanorequalto == equalityequalto != inequalitynotequalto Table11.2 Exercise11.1 Solutiononp.141. EvaluatethefollowingBooleanexpressions: 1.9 < 25 2.9 < 3 3.9 > 14 4.9 < =17 5.9 > =25 6.9==13 7.9!=13 8.9! < 25 TheanswerstoBooleanexpressionswithintheC++programminglanguageareavalueofeither1fortrue or0forfalse. Becareful.Inmathyouarefamiliarwithusingthissymbol=tomeanequaland 6 = tomeannot equal.IntheC++programminglanguagethe 6 = isnotusedandthe=symbolmeansassignment. 11.3.2DemonstrationPrograminC++ 11.3.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: 3 Thiscontentisavailableonlineat.

PAGE 145

137 Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 11.3.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele.Followingthemethods ofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunctionwith otherlearningmaterials. DownloadfromConnexions:Demo_Relational_Operators.cpp 4 11.4CompoundStatement 5 11.4.1TheNeedforaCompoundStatement Forillustrationwewillusethesyntaxforthe ifthenelse controlstructurewithintheC++programming language.Howeverthisproblemgenerallyexitsforallcontrolstructureswithinanylanguagethatrequires theuseofcompoundstatements.Thesyntaxis: ifexpression statement; else statement; WithintheC++programminglanguagetherecanbe onlyonestatementlistedastheactionpart ofacontrolstructure .Often,wewillwanttodomorethanonestatement.Thisproblemisovercome bycreatinga compoundstatement .Thebracesymbolstheopening{andtheclosing}-areusedto createacompoundstatement.Forexample: ifexpression { statement; statement; } else { statement; statement; } Becauseprogrammersoftenforgetthattheycanhave onlyonestatementlistedastheactionpart ofacontrolstructure ;theC++programmingindustryencouragestheuseofindentationtoseethe actionpartsclearlyandtheuseofcompoundstatements braces ,evenifthereisonlyoneaction.Thus: ifexpression { 4 Seetheleat 5 Thiscontentisavailableonlineat.

PAGE 146

138 CHAPTER11.11.TWOWAYSELECTION statement; } else { statement; } Bywritingcodeinthismanner,iftheprogrammermodiesthecodebyaddingmorestatementstoeither theactiontrueortheactionfalse;theywillnotintroduceeithercompilerorlogicerrors.Usingindentation andbracesshouldbecomestandardpracticeforC++programmersandprogrammersinanyotherlanguage thatrequiretheuseofcompoundstatementswiththecontrolstrucutes. 11.4.2OtherUsesofaCompoundStatement "Acompoundstatementisaunitofcodeconsistingofzeroormorestatements.Itisalsoknownasa block Thecompoundstatementallowsagroupofstatementstobecomeonesingleentry.Youusedacompound statementinyourrstprogramwhenyouformedthebodyofthefunctionmain.AllC++functionscontain acompoundstatementknownasthefunctionbody. Acompoundstatementconsistofanopeningbrace,optionaldeclarations,denitions,andstatements, followedbyaclosingbrace.Althoughallthreeareoptional,oneshouldbepresent." 6 11.4.3Denitions Denition11.6:compoundstatement Aunitofcodeconsistingofzeroormorestatements. Denition11.7:block Anothernameforacompoundstatement. 11.5Practice11:TwoWaySelection 7 11.5.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Givenpseudocode,writetheC++codeforaprogramthatusestheifthenelsecontrolstructure. 11.5.2MemoryBuildingActivities Linkto:MBA11 8 6 BehrouzA.ForouzanandRichardF.Gilberg, Computer Science A Structured Approach using C++ Second EditionUnited StatesofAmerica:ThompsonBrooks/Cole,2004100. 7 Thiscontentisavailableonlineat. 8 Seetheleat

PAGE 147

139 11.5.3Exercises Exercise11.2 Solutiononp.141. EvaluatethefollowingBooleanexpressions: 1.25 < 7 2.3 < 7 3.14 > 7 4.17 < =7 5.25 > =7 6.13==7 7.9!=7 8.5! > 7 11.5.4MiscellaneousItems Linkto:Animatedgifshowingifthenelse 9 Linkto:ManipulationofDataPart2 10 11.5.5LabAssignment 11.5.5.1CreatingaFolderorSub-FolderforChapter11Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_11withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 11.5.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_11_Pseudocode.txt 11 11.5.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefromtheLab_11_Pseudocode.txtle.Nameit:Lab_11.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 9 Seetheleat 10 Seetheleat 11 Seetheleat

PAGE 148

140 CHAPTER11.11.TWOWAYSELECTION 11.5.6Problems 11.5.6.1Problem11aInstructions Createatablewiththesixrelationaloperatorsandtheirmeanings. 11.5.6.2Problem11bInstructions Explainwhyweareusingthe"ifthenelse"tomanipulatetheinputdataintheexamplebelow. Example11.1:C++sourcecode cout n nEnteronesideoftherectangle--------> :"; cin side1; cout n nEntertheothersideoftherectangle--> :"; cin side2; ifside1 > side2 { length=side1; width=side2; } else { length=side2; width=side1; }

PAGE 149

141 SolutionstoExercisesinChapter11 SolutiontoExercise11.1p.136 Answers: 1.1 2.0 3.0 4.1 5.0 6.0 7.1 8.Error,the"notlessthan"isnotavalidoperator. SolutiontoExercise11.2p.139 Answers: 1.0 2.1 3.1 4.0 5.1 6.0 7.1 8.Error,thenotgreaterthanisnotavalidoperator.

PAGE 150

142 CHAPTER11.11.TWOWAYSELECTION

PAGE 151

Chapter12 12.MultiwaySelection 12.1NestedIfThenElse 1 12.1.1IntroductiontoMulitwaySelection 12.1.1.1NestedControlStructures Wearegoingtorstintroducetheconceptofnestedcontrolstructures.Nestingisaconceptthatplacesone iteminsideofanother.Consider: ifexpression trueaction else falseaction Thisisthebasicformoftheifthenelsecontrolstructure.Nowconsider: ifageislessthan18 youcan'tvote ifageislessthan16 youcan'tdrive else youcandrive else youcanvote ifageislessthan21 youcan'tdrink else youcandrink Asyoucanseewesimplyincludedaspartofthe"trueaction"astatementandanotherifthenelse controlstructure.Wedidthesamenestedanotherifthenelseforthe"falseaction".Inourexamplewe nestedifthenelsecontrolstructures.Nestingcouldhaveanifthenelsewithinawhileloop.Thus,the conceptofnestingallowsthemixingofthedierentcategoriesofcontrolstructures. 1 Thiscontentisavailableonlineat. 143

PAGE 152

144 CHAPTER12.12.MULTIWAYSELECTION 12.1.1.2MultiwaySelection Oneofthedrawbacksoftwowayselectionisthatwecanonlyconsidertwochoices.Butwhatdoyoudoif youhavemorethantwochoices.Considerthefollowingwhichhasfourchoices: ifageequalto18 youcannowvote else ifageequalto39 youaremiddleaged else ifageequalto65 youcanconsiderretirement else yourageisunimportant Yougetanappropriatemessagedependingonthevalueofage.Thelastitemisreferredtoasthedefault. Iftheageisnotequalto18,39or65yougetthedefaultmessage.Insomesituationsthereisnodefault action.Consider: ifageequalto18 youcannowvote else ifageequalto39 youaremiddleaged else ifageequalto65 youcanconsiderretirement Thelastifthenelsecontrolstructurehasno"else".It'simplied"elsedonothing".Withoutthedefault themultiwayselectioncouldbewrittenasaseriesof"ifthenwithouttheelse"structures.Consider: ifageequalto18 youcannowvote ifageequalto39 youaremiddleaged ifageequalto65 youcanconsiderretirement Wehaveshowntwowaystoaccomplishmultiwayselection.Thechoiceofusingnesteditthenelsecontrol structuresoraseriesofifthencontrolstructuresisdecidedontheexistenceofadefaultactionyoumust usenestedifthenelseorprogrammerpreferenceifthereisnotadefaultactionyoumayusenestedifthen elseoraseriesofifthencontrolstructures. 12.1.2ifthenelseSyntaxwithinC++ ThesyntaxfortheifthenelsecontrolstructurewithintheC++programminglanguageis: Example12.1:C++sourcecode:Layoutofanifthenelse

PAGE 153

145 ifexpression { statement; } else { statement; } note: Thetestexpressioniswithintheparentheses,butthisisnotafunctioncall.Theparentheses arepartofthecontrolstructure.Additionally,thereisnosemicolonaftertheparenthesisfollowing theexpression. 12.1.3C++Example Multiwayselectionisoftenneededtocoverallpossibilities.Assumethattheuserhasbeenpromptedfor theagesoftwopeoplewiththeanswersstoredinvariablesnamedage1andage2.Consider: Example12.2:C++sourcecode ifage1 > age2 { cout n n n nThefirstpersonisolder."; } else { cout n n n nThesecondpersonisolder."; } Whatifthetwopersonsarethesameage?Theprogramincorrectlysaysthesecondpersonisolder.To solvethiswemusthandleallthreepossibilities.Considerthismulitwayselectionexample: Example12.3:C++sourcecode ifage1==age2 { cout n n n nTheyarethesameage."; } else { ifage1 > age2 { cout n n n nThefirstpersonisolder."; } else

PAGE 154

146 CHAPTER12.12.MULTIWAYSELECTION { cout n n n nThesecondpersonisolder."; } } 12.1.4Denitions Denition12.1:nestedcontrolstructures Placingonecontrolstructureinsideofanother. Denition12.2:multiwayselection Usingcontrolstructurestobeabletoselectfrommorethantwochoices. 12.2LogicalOperators 2 12.2.1OverviewoftheLogicalOperators Withinmostlanguages,expressionsthatyieldBooleandatatypevaluesaredividedintotwogroups.One groupusestherelationaloperatorswithintheirexpressionsandtheothergroupuseslogicaloperatorswithin theirexpressions. Thelogicaloperatorsareoftenusedtohelpcreatea testexpression thatcontrolsprogramow.This typeofexpressionisalsoknownasa Booleanexpression becausetheycreateaBooleananswerorvalue whenevaluated.TheanswerstoBooleanexpressionswithintheC++programminglanguageareavalue ofeither1fortrueor0forfalse.TherearethreecommonlogicaloperatorsthatgiveaBooleanvalueby manipulatingotherBooleanoperands.Operatorsymbolsand/ornamesvarywithdierentprogramming languages.TheC++programminglanguageoperatorswiththeirmeaningsare: C++Operator Meaning Comment Typing && Logicaland twoampersands || Logicalor twoverticaldashesorpipingsymbols Logicalnot unary theexclamationpoint Table12.1 Inmostlanguagestherearestrictrulesforformingproperlogicalexpressions.Anexampleis: 6 > 4&&2 < =14 Thisexpressionhastworelationaloperatorsandonelogicaloperator.Usingtheprecedenceofoperator rulesthetworelationalcomparisonswillbedonebeforethelogicalandoperation.Thus: 1&&1 or true&&true Thenalevaluationoftheexpressionis:1meaningtrue. WecansaythisinEnglishas:Itistruethatsixisgreaterthanfourandthattwoislessthanorequal tofourteen. Whenforminglogicalexpressionsprogrammersoftenuseparenthesesevenwhennottechnicallyneeded tomakethelogicoftheexpressionveryclear.ConsidertheabovecomplexBooleanexpressionrewritten: > 4&& < =14 2 Thiscontentisavailableonlineat.

PAGE 155

147 12.2.2TruthTables Acommonwaytoshowlogicalrelationshipsisintruthtables. Logicaland&& x y x&&y false false false false true false true false false true true true Table12.2 Logicalor|| x y x||y false false false false true true true false true true true true Table12.3 Logicalnot! x !x false true true false Table12.4 12.2.3Examples IcallthisexampleofwhyIhate"and"andlove"or". EverydayasIcamehomefromschoolonMondaythroughThursday;Iwouldaskmymother,"MayIgo outsideandplay?"Shewouldanswer,"Ifyourroomiscleanandyourhomeworkisdonethenyoumaygo outsideandplay."Ilearnedtohatetheword"and".Icouldmanagetogetoneofthetasksdoneandhave sometimetoplaybeforedinner,butbothofthem ::: well,Ihated"and". OnFridaymymothertookamorerelaxedviewpointandwhenaskedifIcouldgooutsideandplayshe responded,"Ifyourroomiscleanoryourhomeworkisdonethenyoumaygooutsideandplay."Ilearned tocleanmyroomquicklyonFridayafternoon.Wellneedlesstosay,Iloved"or". Forthenextexample,justimagineateenagertalkingtotheirmother.Duringtheconversationmom says,"Afterall,yourDadisreasonable!"Theteenagersays,"Reasonable.shortpauseNot." Maybecollegeprofessorswillthinkthatalltheirstudentsstudiedfortheexam.Haha!Not.Well,I hopeyougetthepoint. Exercise12.1 Solutiononp.159. EvaluatethefollowingLogicalBooleanexpressions:

PAGE 156

148 CHAPTER12.12.MULTIWAYSELECTION 1.25 < 7||15 > 36 2.15 > 36||3 < 7 3.14 > 7&&5 < =5 4.4 > 3&&17 < =7 5.!false 6.!!=7 7.9!=7&&!0 8.5 > &&7 12.2.4DemonstrationPrograminC++ 12.2.4.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 12.2.4.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele.Followingthemethods ofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunctionwith otherlearningmaterials. DownloadfromConnexions:Demo_Logical_Operators.cpp 3 12.2.5Denitions Denition12.3:logicaloperator AnoperatorusedtocreatecomplexBooleanexpressions. Denition12.4:truthtables Acommonwaytoshowlogicalrelationships. 12.3CaseControlStructure 4 12.3.1TraditionalCaseControlStructure 12.3.1.1MultiwaySelectionusingtheCaseStructure Oneofthedrawbacksoftwowayselectionisthatwecanonlyconsidertwochoices.Butwhatdoyoudoif youhavemorethantwochoices.Considerthefollowingwhichhasfourchoices: ifageequalto18 youcanvote else 3 Seetheleat 4 Thiscontentisavailableonlineat.

PAGE 157

149 ifageequalto39 you'remiddleaged else ifageequalto65 considerretirement else ageisun-important Yougetanappropriatemessagedependingonthevalueofage.Thelastitemisreferredtoasthedefault. Iftheageisnotequalto18,39or65yougetthedefaultmessage.Insomesituationsthereisnodefault action.Considerthisowchartexample: Figure12.1 Thisowchartisofthecasecontrolstructureandisusedformultiwayselection.Thedecisionboxholds thevariableage.Thelogicofthecaseisoneofequalitywhereinthevalueinthevariableageiscompared tothelistedvaluesinorderfromlefttoright.Thus,thevaluestoredinageiscomparedto18oris"age equalto18".Ifitistrue,thelogicowsdownthroughtheactionanddropsoutatthebottomofthecase structure.Ifthevalueofthetestexpressionisfalse,itmovestothenextlistedvaluetotherightandmakes anothercomparison.Itworksexactlythesameasournestedifthenelsestructure.

PAGE 158

150 CHAPTER12.12.MULTIWAYSELECTION 12.3.1.2C++CodetoAccomplishMultiwaySelection Usingthesameexampleasabove,hereistheC++codetoaccomplishthecasecontrolstructure. Example12.4:C++sourcecode switchage { case18:cout n nYoucanvote."; break; case39:cout n nYou'remiddleaged."; break; case65:cout n nConsiderretirement."; break; default:cout n nAgeisun-important."; } TherstthingyoushouldnoteisthattheC++programminglanguagedoesnotformallyhaveacasecontrol structure.Itdoeshaveaswitchcontrolstructurebutitactsdierentlythanthetraditionalcasecontrol structure.Weuseabreakwhichisabranchingcontrolstructurewiththeswitchtomakeitactlikethe traditionalcasestructure.Thisisoneofthefewallowablewaystousetheswitchwithbreakwithinthe C++programminglanguagetosimulatethetraditionalcasestructure.Allotherusesoftheswitchorbreak aretobeavoidedifyouaretostaywithintheboundsofgoodstructuredprogrammingtechniques. Thevalueinthevariableageiscomparedtotherst"case"Note:ItisoneoftheC++reservedwords. whichisthevalue18usinganequalitycomparisonoris"ageequalto18".Ifitistrue,thecoutisexecuted whichdisplaysYoucanvote.andthenextlineofcodethebreakisdonewhichjumpsustotheendof thecontrolstructure.Ifitisfalse,itmovesontothenextcaseforcomparison. 12.3.2LimitationsoftheCaseControlStructure MostprogramminglanguagesincludingC++requirethelistedvaluesforthecasecontrolstructurebeof theintegerfamilyofdatatypes.Thisbasicallymeanseitheranintegerorcharacterdatatype.Additionally, rangesofvaluesarenotallowed.Considerthisowchartingexamplethatusedranges:

PAGE 159

151 Figure12.2 Consideralsothefollowingpseudocodeforthesamelogic: Caseofage 0to17Display"Youcan'tvote." 18to64Display"You'reinyourworkingyears." 65+Display"Youshouldberetired." Endcase Usingthecasecontrolstructurewhenusingnonintegerfamilyorrangesofvaluesisallowedwhendesigningaprogramanddocumentingthatdesignwithpseudocodeorowcharting.However,theimplementation inmostlanguageswouldfollowa nestedifthenelse approachwithcomplexBooleanexpressions.The logicoftheaboveexampleswouldlooklikethis: ifage > 0andage < =to17 displayYoucan'tvote. else ifageis > =18andage < =64

PAGE 160

152 CHAPTER12.12.MULTIWAYSELECTION displayYou'reinyourworkingyears. else displayYoushouldberetired. 12.3.3GoodStructuredProgrammingMethods Mosttextbookauthorsconrmthatgoodstructuredprogrammingtechniquesandhabitsaremoreimportant thanconcentratingonthetechnicalpossibilitiesandcapabilitiesofthelanguagethatyouareusingtolearn programmingskills.Remember,thismoduleisconcentratingonprogrammingfundamentalsandconcepts anditusestheC++programminglanguagetobuildourinitialprogrammingskills.Itisnotacreatedwith theintenttocovertheC++programminglanguageindetail,despitethefactthatattimeswehavetocover C++languagemechanics. 12.3.4Denitions Denition12.5:case Acontrolstructurethatdoesmulitwayselection. Denition12.6:switch AC++controlstructurethatcanbemadetoactlikeacasecontrolstructure. 12.4BranchingControlStructures 5 12.4.1Discussion Thebranchingcontrolstructuresallowtheowofexecutiontojumptoadierentpartoftheprogram.The threecommonbranchingcontrolstructuresare:break,continueandgoto.Thesearerarelyusedinmodular structuredprogrammingwithoneexception.Thatexceptionisinrelationtocreatingthecasewithinthe selectioncategoryofcontrolstructures.Thereisoneotherbranchingcontrolstructurethatisoftennot viewedasbranchingcontrolstructure.Itis:return.Additionally,wewilladdtoourlistofbranchingitems apre-denedfunctioncommonlyusedintheC++programminglanguageof:exitthatispartoftheC standardlibrarycstdlib.Somedenitions: 12.4.1.1Denitions Denition12.7:branchingcontrolstructures Allowtheowofexecutiontojumptoadierentpartoftheprogram. Denition12.8:break Abranchingcontrolstructurethatterminatestheexistingstructure. Denition12.9:continue Abranchingcontrolstructurethatcausesalooptostopitscurrentiterationandbeginthenext one. Denition12.10:goto Abranchingcontrolstructurethatcausesthelogictojumptoadierentplaceintheprogram. Denition12.11:return Abranchingcontrolstructurethatcausesafunctiontojumpbacktothefunctionthatcalledit. Denition12.12:exit Apre-denedfunctionusedtoprematurelystopaprogramandjumptotheoperatingsystem. 5 Thiscontentisavailableonlineat.

PAGE 161

153 Wewilldiscusseachitemindicatingwhichonesareallowedornotallowedwithingoodstructured programmingpractices. 12.4.2Examples 12.4.2.1break Thebreakisusedinoneoftwoways;withtheswitchaC++programmingstructuretomakeitactlikea casestructureit'smorecommonnamewithinmostprogramminglanguagesoraspartofaloopingprocess tobreakoutoftheloop.Therstusageisallowedingoodstructuredprogrammingandthesecondisnot allowedingoodstructuredprogramming. Example12.5:C++sourcecode switchage { case18:cout n nYoucanvote."; break; case39:cout n nYouaremiddleaged."; break; case65:cout n nYouareatretirementage."; break; default:cout n nYourcurrentageisnotimportant."; } Thefollowingisanunauthorizeduseofbreakinaloopanditgivestheappearancethattheloopwillexecute 8times,butthebreakstatementcausesittostopduringthefthiteration. Example12.6:C++sourcecode counter=0; whilecounter < 8 { cout counter endl; ifcounter==4 { break; } counter++; } 12.4.2.2continue Thecontinuestructureisnotallowedingoodstructuredprogramming.Thefollowinggivestheappearance thattheloopwillprinttothemonitor8times,butthecontinuestatementcausesitnottoprintnumber4. Example12.7:C++sourcecode

PAGE 162

154 CHAPTER12.12.MULTIWAYSELECTION forcounter=0;counter < 8;counter++ { ifcounter==4 { continue; } cout counter endl; } 12.4.2.3goto Thegotostructureisnotallowedingoodstructuredprogramming.Itiswithacertainamountofhesitancy thatweevenshowit.Manytextbooksdonotcoverthegoto.WithintheC++programminglanguageyou createalabelwithanidentiernamefollowedbyacolon.Youusethecommandwordgotofollowedbythe label.Alabelcanbeusedbeforeitisdeclared. Example12.8:C++sourcecode somelinesofcode; gotomynewspot;//jumpstothelabel somelinesofcode; somelinesofcode; somelinesofcode; mynewspot:somestatement;//Declaredlabel somelinesofcode; 12.4.2.4return Thereturnisallowedingoodstructuredprogramming,butonlyattheendofafunction.Afunctionshould notpre-maturelyendbyhavingthelogicofthefunctionhaveitterminatebyjumpingbacktothefunction thatcalledit. Example12.9:C++sourcecode //****************************************************** //getdata //****************************************************** voidget_datavoid { //Input-TestData-5678.9,5432.1 cout n nEnterthelengthofthepropertyinfeet--> :"; cin property_length; cout n nEnterthewidthofthepropertyinfeet---> :";

PAGE 163

155 cin property_width; return; } 12.4.2.5exit Althoughexitistechnicallyapre-denedfunction,itiscoveredherebecauseofitscommonusageinprogramming.Agoodexampleistheopeningaleandthentestingtoseeifthelewasactuallyopened.If not,wehaveanerrorthatusuallyindicatesthatwewanttopre-maturelystoptheexecutionoftheprogram. WithintheC++programminglanguagetheexitfunctionterminatestherunningoftheprogramandinthe processreturnsanintegervaluebacktotheoperatingsystem.Ittsthedenitionofbranchingwhichisto jumptosomeotherplaceintheprogram.Inourexamplethevaluereturnedtotheoperatingsystemisthe valueoftheconstantnamed:EXIT_FAILURE. Example12.10:C++sourcecode inData.openfilename;//Openinputfile if!inData//Testtoseeiffilewasopened { cout n n n nErroropeningfile:" filename n n n n"; pause;//Pause-userreadsmessage exitEXIT_FAILURE;//Allowsapre-maturejumptoOS } 12.5Practice12:MultiwaySelection 6 12.5.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Identifywhichselectioncontrolstructuresaretwo-wayselectionandwhicharemultiwayselection. 3.Understand,deneand/orexplaincase,switchandnestedifthenelse. 4.Beabletowritepseudocodeorowchartingforthecasecontrolstructure. 5.BeabletowriteC++sourcecodeforacasestructureusingequalityandlistedvaluesswitchwith breaktoactlikeacasestructure. 6.BeabletowriteC++sourcecodeforacasestructureusingrangesofvaluesoroating-pointvalues nestedifthenelsetoactlikeacasestructure. 7.Whenfeasible,beabletoconvertC++sourcecodefromswitchactinglikeacasetonestedifthenelse andviceversa. 6 Thiscontentisavailableonlineat.

PAGE 164

156 CHAPTER12.12.MULTIWAYSELECTION 12.5.2MemoryBuildingActivities Linkto:MBA12 7 12.5.3Exercises Exercise12.2 Solutiononp.159. EvaluatethefollowingLogicalBooleanexpressions: 1.25 > 39||15 > 36 2.19 > 26||13 < 17 3.14 < 7&&6 < =6 4.4 > 3&&17 > =7 5.!true 6.!==7 7.9!=7&&!1 8.6 < &&8 12.5.4MiscellaneousItems Linkto:ManipulationofDataPart3 8 12.5.5LabAssignment 12.5.5.1CreatingaFolderorSub-FolderforChapter12Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_12withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 12.5.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_12a.cpp 9 12.5.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CompileandruntheLab_12a.cppsourcecodele.Understandhowitworks. CopythesourcecodeleLab_12a.cppnamingit:Lab_12b.cpp Convertthenestedifthenelsetoaswitchwithbreaks. Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 7 Seetheleat 8 Seetheleat 9 Seetheleat

PAGE 165

157 12.5.6Problems 12.5.6.1Problem12aInstructions Flowchartthefollowingpseudocode: Example12.11:pseudocode Caseofshoe_size 4to6Display"Small." 7to9Display"Medium." 10+Display"Large." Endcase 12.5.6.2Problem12bInstructions The"Flip-Flops"isauniqueshoestorethatonlysellsip-ops.Adultshoesizeslessthan4arehandledin thechildren'sdepartment,thuswedon'tneedtoconcernourselveswithsizeslessthan4.Halfshoesizesare toberoundeddown,thustheprompttotheuserthathappensbeforethiscasestructurewillhaveaddressed thatissue.Thevariableshoe_sizewillbeanintegervaluebetween4and1,000,000,000onebillion. WriteC++sourcecodeforthefollowingpseudocode: Example12.12:pseudocode Caseofshoe_size 4to6Display"Small." 7to9Display"Medium." 10+Display"Large." Endcase 12.5.6.3Problem12cInstructions WriteC++sourcecodeforthefollowingpseudocode: Example12.13:pseudocode Ifageequalto24 Displayamessage"You'rethesameageasMelinda." Else Ifageequalto27 Displayamessage"You'rethesameageasRuth." Else Ifageequalto34 Displayamessage"You'rethesameageasBen." Else

PAGE 166

158 CHAPTER12.12.MULTIWAYSELECTION Displayamessage"You'reageisun-important." Endif Endif Endif

PAGE 167

159 SolutionstoExercisesinChapter12 SolutiontoExercise12.1p.147 Answers: 1.0 2.1 3.1 4.0 5.1 6.0 7.1 8.Error,thereneedstobeanoperandbetweentheoperators > and&&. SolutiontoExercise12.2p.156 Answers: 1.0 2.1 3.0 4.1 5.0 6.1 7.0 8.Error,thereneedstobeanoperandbetweentheoperators < and&&.

PAGE 168

160 CHAPTER12.12.MULTIWAYSELECTION

PAGE 169

Chapter13 13.TestAfterLoops 13.1DoWhileLoop 1 13.1.1IntroductiontoTestAfterLoops Therearetwocommonlyusedtestafterloopsintheiterationorrepetitioncategoryofcontrolstructures. Theyare:dowhileandrepeatuntil.Thismodulecoversthe:dowhile. 13.1.1.1UnderstandingIterationinGeneraldowhile Theconceptofiterationisconnectedtopossiblywantingtorepeatanaction.Likeallcontrolstructureswe askaquestiontocontroltheexecutionoftheloop.Thetermloopcomesfromthecircularloopingmotion thatoccurswhenusingowcharting.Thebasicformofthedowhileloopisasfollows: do somestatementsoraction somestatementsoraction somestatementsoraction updatetheflag whiletheanswertothequestionistrue IneverylanguagethatIknowthequestioncalleda testexpression isa Booleanexpression .The Booleandatatypehastwovaluestrueandfalse.Let'srewritethestructuretoconsiderthis: do somestatementsoraction somestatementsoraction somestatementsoraction updatetheflag whileexpressionistrue Withinthedowhilecontrolstructuretherearethreeattributesofaproperlyworkingloop.Theyare: Actionoractions Updateoftheag 1 Thiscontentisavailableonlineat. 161

PAGE 170

162 CHAPTER13.13.TESTAFTERLOOPS Testexpression TheEnglishphrasingis,"Youdotheactionwhiletheexpressionistrue".Thisisloopingonthetrue.When thetestexpressionisfalse,youstoptheloopandgoonwiththenextitemintheprogram.Notice,because thisisatestafterlooptheactionwillalwayshappen atleastonce .Itiscalleda testafterloop because thetestcomesaftertheaction.Itisalsosometimescalledapost-testloop,meaningthetestispostor Latinforaftertheactionandupdate. 13.1.2ThedowhileStructurewithinC++ 13.1.2.1Syntax ThesyntaxforthedowhilecontrolstructurewithintheC++programminglanguageis: do { statement; statement; statement; statement;//Thisstatementupdatestheflag; } whileexpression; note: Thetestexpressioniswithintheparentheses,butthisisnotafunctioncall.Theparentheses arepartofthecontrolstructure.Additionally,thereisasemicolonaftertheparenthesisfollowing theexpression. 13.1.2.2AnExample Example13.1:C++sourcecode:dowhileloop do { cout n nWhatisyourage?"; cin age_user; cout n nWhatisyourfriend'sage?"; cin age_friend; cout n nTogetheryouragesaddupto:"; cout age_user+age_friend; cout n nDoyouwanttodoitagain?yorn"; cin loop_response; } whileloop_response=='y'; Thethreeattributesofatestafterlooparepresent.Theactionpartconsistsofthe6linesthatprompt fordataandthendisplaysthetotalofthetwoages.Theupdateoftheagisthedisplayingthequestion andgettingtheanswerforthevariableloop_response.Thetestistheequalityrelationalcomparisonofthe valueintheagvariabletothelowercasecharacterofy.

PAGE 171

163 Thistypeofloopcontroliscalledaneventcontrolledloop.Theagupdatingisaneventwheresomeone decidesiftheywantthelooptoexecuteagain. Usingindentationwiththealignmentoftheloopactionsandagupdateisnormalindustrypractice withintheC++community. 13.1.2.3InniteLoops Atthispointit'sworthmentioningthatgoodprogrammingalwaysprovidesforamethodtoinsurethatthe loopquestionwilleventuallybefalsesothattheloopwillstopexecutingandtheprogramcontinueswith thenextlineofcode.However,ifthisdoesnothappenthentheprogramisinaninniteloop.Inniteloops areabadthing.Considerthefollowingcode: Example13.2:C++sourcecode:inniteloop loop_response='y'; do { cout n nWhatisyourage?"; cin age_user; cout n nWhatisyourfriend'sage?"; cin age_friend; cout n nTogetheryouragesaddupto:"; cout age_user+age_friend; } whileloop_response=='y'; Theprogrammerassignedavaluetotheagbeforetheloopandforgottoupdatetheag.Everytime thetestexpressionisaskeditwillalwaysbetrue.Thus,aninniteloopbecausetheprogrammerdidnot provideawaytoexittheloopheforgottoupdatetheag. Considerthefollowingcode: Example13.3:C++sourcecode:inniteloop do { cout n nWhatisyourage?"; cin age_user; cout n nWhatisyourfriend'sage?"; cin age_friend; cout n nTogetheryouragesaddupto:"; cout age_user+age_friend; cout n nDoyouwanttodoitagain?yorn"; cin loop_response; } whileloop_response='y'; Nomatterwhattheuserrepliesduringtheagupdate,thetestexpressiondoesnotdoarelationalcomparison butdoesanassignment.Itassigns'y'tothevariableandasksif'y'istrue?Sinceallnon-zerovaluesare treatedasrepresentingtruewithintheBooleanconceptsoftheC++programminglanguage,theanswerto thetextquestionistrue.Viola,youhaveaninniteloop.

PAGE 172

164 CHAPTER13.13.TESTAFTERLOOPS 13.1.3Denitions Denition13.1:dowhile AtestafteriterationcontrolstructureavailableinC++. Denition13.2:actionitem Anattributeofiterationcontrolstructures. Denition13.3:updateitem Anattributeofiterationcontrolstructures. Denition13.4:testitem Anattributeofiterationcontrolstructures. Denition13.5:atleastonce Indicatingthattestafterloopsexecutetheactionatleastonce. Denition13.6:inniteloop Nomethodofexit,thusabadthing. 13.2FlagConcept 2 13.2.1ConceptDiscussion Forcenturiesagshavebeenusedasasignaltoletothersknowsomethingaboutthegrouporindividual thatisdisplaying,yingorwavingtheag.Therearecountryagsandstateags.Shipsatseaewthe agoftheircountry.Piratesewtheskullandcrossbones.Ayellowagwasusedforquarantine,usually theplague.Evenpiratesstayedaway.Today,somepeoplemightrecognizetheagusedbyscubadivers. ThePresidentsofmostcountrieshaveaag.Ataracecareventtheyusethecheckeredagtoindicatethe raceisover. 2 Thiscontentisavailableonlineat.

PAGE 173

165 Figure13.1 Computerprogrammingusestheconceptofaaginthesamewaythatphysicalagsareused.Aag isanythingthatsignalssomeinformationtothepersonlookingatit. 13.2.2ComputerImplementation Anyvariableorconstantthatholdsdatacanbeusedasaag.Youcanthinkofthestoragelocationas aagpole.Thevaluestoredwithinthevariableconveyssomemeaningandyoucanthinkofitasbeing theag.Anexamplemightbeavariablenamed:genderwhichisofthecharacterdatatype.Thetwo valuesnormallystoredinthevariableare:'F'and'M'meaningfemaleandmale.Then,somewherewithin aprogramwemightlookatthevariabletomakeadecision: Example13.4:agcontrolinganifthencontrolstructure ifgenderequals'F' display"Areyoupregnant?" getanswerfromuserstoreinpregnantvariable

PAGE 174

166 CHAPTER13.13.TESTAFTERLOOPS Lookingattheagimpliescomparingthevalueinthevariabletoanothervalueaconstantorthevaluein anothervariableusingarelationaloperatorinouraboveexample:equality. Controlstructuresare"controlled"byusinga testexpression whichisusuallya Booleanexpression .Thus,theagconceptof"looking"atthevalueinthevariableandcomparingittoanothervalueis fundamentaltounderstandinghowallcontrolstructureswork. 13.2.3TwoFlagswiththeSameMeaning Sometimeswewilluseaniterationcontrolstructureofdowhiletoallowustodecideifwewanttodothe loopactionagain.Avariablemightbenamed"loop_response"withtheuserpromptedfortheiranswerof 'y'foryesor'n'forno.Oncetheanswerisretrievedfromthekeyboardandstoredinouragvariableof "loop_response"thetestexpressiontocontroltheloopmightbe: Example13.5:simpleagcomparison loop_responseequals'y' Thisisnebutwhatiftheuseraccidentallyhasonthecapslock.Thenhisresponseof'Y'wouldnot havethecontrolstructureloopandperformtheactionagain.Thesolutionliesinlookingattheagtwice. Consider: Example13.6:complexagcomparison loop_responseequals'y'orloop_responseequals'Y' WelooktoseeiftheagiseitheralowercaseyoranuppercaseYbyusingamorecomplexBoolean expressionwithbothrelationalandlogicaloperators. 13.2.4MultipleFlagsinOneByte Withinassemblylanguageprogrammingandinmanytechnicalprogramsthatcontrolspecialdevices;the useofasinglebytetorepresentseveralagsiscommon.Thisisaccomplishedbyhavingeachoneofthe8 bitsthatmakeupthebyterepresentaag.Eachbithasavalueofeither1or0andcanrepresenttrueand false,onoro,yesorno,etc. 13.2.5Denitions Denition13.7:ag Avariableorconstantusedtostoreinformationthatwillnormallybeusedtocontroltheprogram. 13.3AssignmentvsEqualitywithinC++ 3 13.3.1GeneralDiscussion Mostcontrolstructuresusea testexpression thatexecuteseitherselectionasinthe:ifthenelseor iterationasinthewhile;dowhile;orforloopsbasedonthetruthfulnessorfalsenessoftheexpression.Thus, 3 Thiscontentisavailableonlineat.

PAGE 175

167 weoftentalkaboutthe Booleanexpression thatiscontrollingthestructure.Withinmanyprogramming languages,thisexpressionmustbeaBooleanexpressionandisgovernedbyatightsetofrules.However,in C++everydatatypecanbeusedasaBooleanexpression,becauseeverydatatypecanbedemotedintoa Booleanvaluebyusingtherule/conceptthatzerorepresentsfalseandallnon-zerovaluesrepresenttrue. WithinC++wehavethepotentialaddedconfusionoftheequalssymbolasanoperatorthatdoesnot representthenormalmathmeaningof equality thatwehaveusedformostofourlife.Theequalssymbol withC++means: assignment .TogettheequalityconceptofmathwithinC++weusetwoequalsymbols torepresenttherelationaloperatorofequality.Let'sconsider: ifpig='y' { cout n nPigsaregood"; } else { cout n nPigsarebad."; } Thetestexpressionofthecontrolstructurewillalwaysbetrue,becausetheexpressionisanassignment nottherelationaloperatorof==.Itassignsthe'y'tothevariablepig,thenlooksatthevalueinpigand determinesthatitisnotzero;thereforetheexpressionistrue.Anditwillalwaysbetrueandtheelsepart willneverbeexecuted.Thisisnotwhattheprogrammerhadintended.Let'sconsider: do { cout n nPigsaregood"; cout n nDoitagain,answeryorn:"; cin do_it_again } whiledo_it_again='y'; Theloop'stestexpressionwillalwaysbetrue,becausetheexpressionisanassignmentnottherelational operatorof==.Itassignsthe'y'tothevariabledo_it_again,thenlooksatthevalueindo_it_againand determinesthatitisnotzero;thereforetheexpressionistrue.Anditwillalwaysbetrueandyouhavejust createdaninniteloop.Asareminder,inniteloopsarenotagoodthing. Theseexamplesaretoremindyouthatyoumustbecarefulincreatingyourtestexpressionssothatthey areindeedaquestionusuallyinvolvingtherelationaloperators. Don'tgetcaughtusingassignmentforequality. 13.4RepeatUntilLoop 4 13.4.1IntroductiontoTestAfterLoops Therearetwocommonlyusedtestafterloopsintheiterationorrepetitioncategoryofcontrolstructures. Theyare:dowhileandrepeatuntil.Thismodulecoversthe:repeatuntil. 4 Thiscontentisavailableonlineat.

PAGE 176

168 CHAPTER13.13.TESTAFTERLOOPS 13.4.1.1UnderstandingIterationinGeneralrepeatuntil Theconceptofiterationisconnectedtopossiblywantingtorepeatanaction.Likeallcontrolstructureswe askaquestiontocontroltheexecutionoftheloop.Thetermloopcomesfromthecircularloopingmotion thatoccurswhenusingowcharting.Thebasicformoftherepeatuntilloopisasfollows: repeat somestatementsoraction somestatementsoraction somestatementsoraction updatetheflag untiltheanswertothequestionbecomestrue IneverylanguagethatIknowthequestioncalleda testexpression isa Booleanexpression .The Booleandatatypehastwovaluestrueandfalse.Let'srewritethestructuretoconsiderthis: repeat somestatementsoraction somestatementsoraction somestatementsoraction updatetheflag untilexpressionbecomestrue Withintherepeatuntilcontrolstructuretherearethreeattributesofaproperlyworkingloop.Theyare: Actionoractions Updateoftheag Testexpression TheEnglishphrasingis,"Yourepeattheactionuntiltheexpressionbecomestrue".Thisisloopingonthe false.Whenthetestexpressionbecomestrue,youstoptheloopandgoonwiththenextitemintheprogram. Notice,becausethisisatestafterlooptheactionwillalwayshappen atleastonce .Itiscalleda"test afterloop"becausethetestcomesaftertheaction.Itisalsosometimescalledapost-testloop,meaningthe testispostorLatinforaftertheactionandupdate. 13.4.2TherepeatuntilStructurewithinC++ Well,itjustdoesnotexist.Mostprogramminglanguageshaveeitherthedowhileortherepeatuntilcontrol structures,butnotboth. 13.4.3Denitions Denition13.8:repeatuntil AtestafteriterationcontrolstructurethatisnotavailableinC++. 13.5Practice13:TestAfterLoops 5 13.5.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 5 Thiscontentisavailableonlineat.

PAGE 177

169 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Identifywhichselectioncontrolstructuresaretestafteriteration. 3.Beabletowritepseudocodeorowchartingforthedowhilecontrolstructure. 4.BeabletowriteC++sourcecodeforadowhilecontrolstructure. 13.5.2MemoryBuildingActivities Linkto:MBA13 6 13.5.3Exercises Exercise13.1 Solutiononp.171. Answerthefollowingstatementsaseithertrueorfalse: 1.Thedowhileandrepeatuntilstructureactexactlythesame. 2.Studentssometimesconfuseassignmentandequality. 3.Therepeatuntilloopingcontrolstructureisavailableinallprogramminglanguages. 4.Becauseagsareoftenused,theyareusuallyaspecialdatatype. 5.Thedowhileisatestbeforeloop. 13.5.4MiscellaneousItems Linkto:Animatedgifshowingadowhileloop 7 13.5.5LabAssignment 13.5.5.1CreatingaFolderorSub-FolderforChapter13Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_13withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 13.5.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_13_Pseudocode.txt 8 13.5.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefromtheLab_13_Pseudocode.txtle.Nameit:Lab_13.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 6 Seetheleat 7 Seetheleat 8 Seetheleat

PAGE 178

170 CHAPTER13.13.TESTAFTERLOOPS 13.5.6Problems 13.5.6.1Problem13aInstructions Flowchartthefollowingpseudocode: Example13.7:pseudocode Do Display"Ilikecheesecake!" Display"Doitagain?yorn--> Getanswerfromkeyboard Whileansweris'y'

PAGE 179

171 SolutionstoExercisesinChapter13 SolutiontoExercise13.1p.169 Answers: 1.false 2.true 3.false 4.false 5.false

PAGE 180

172 CHAPTER13.13.TESTAFTERLOOPS

PAGE 181

Chapter14 14.TestBeforeLoops 14.1IncrementandDecrementOperators 1 14.1.1GeneralDiscussion Theideaofincrementordecrementistoeitheraddorsubtract1fromavariablethatisusuallyactingasa ag.Usingavariablenamedcounter;ingenericterms,forexample: incrementthecounter Theconceptis: counterisassignedcounter+1 Thatisyoufetchtheexistingvalueofthecounterandaddonethenstoretheanswerbackintothe variablecounter.Manyprogramminglanguagesallowtheirincrementanddecrementoperatorstoonlybe usedwiththeintegerdatatype.Programmerswillsometimesuseincanddecasabbreviationsforincrement anddecrementrespectively. Operatorsymbolsand/ornamesvarywithdierentprogramminglanguages.TheC++programming languageoperatorswiththeirmeaningsare: C++Operator Meaning ++ increment, twoplussigns decrement, twominussigns Table14.1 14.1.2C++CodeExamples 14.1.2.1BasicConcept WithintheC++programminglanguagetheincrementanddecrementareoftenusedinthissimplegeneric way.Theoperatorofincrementisrepresentedbytwoplussignsinarow.Examples: counter=counter+1; counter+=1; counter++; ++counter; AsC++statements,thefourexamplesalldothesamething.Theyadd1tothevalueofwhatever isstoredincounter.Thedecrementopereatorisrepresentedbytwominussignsinarow.Theywould 1 Thiscontentisavailableonlineat. 173

PAGE 182

174 CHAPTER14.14.TESTBEFORELOOPS subtract1fromthevalueofwhateverwasinthevariablebeingdecremented.Theprecedenceofincrement anddecrementdependsoniftheoperatorisattachedtotherightoftheoperandpostxortotheleftof theoperandprex.WithinC++postxandprexdonothavethesameprecedence. 14.1.2.2PostxIncrement Postxincrementsaystousemyexistingvaluethenwhenyouaredonewiththeotheroperators;increment me.Anexample: intoldest=44;//variablesetupwithinitialization thenlateroninthecode age=oldest++; TherstuseoftheoldestvariableisanRvaluecontextwheretheexistingvalueof44ispulledorfetched andthenassignedtothevariableage;thenthevariableoldestisincrementedwithitsvaluechangingfrom44 to45.Thisseemstobeaviolationofprecedencebecauseincrementishigherprecedencethanassignment. ButthatishowpostxincrementworkswithintheC++programminglanguage. 14.1.2.3PrexIncrement Prexincrementsaystoincrementmenowandusemynewvalueinanycalculation.Anexample: intoldest=44;//variablesetupwithinitialization thenlateroninthecode age=++oldest; Thevariableoldestisincrementedwiththenewvaluechangingitfrom44to45;thenthenewvalueis assignedtoage. Inpostxageisassigned44inprexageisassigned45.Onewaytohelprememberthedierenceisto thinkofpostxasbeingpoliteusemyexistingvalueandreturntoincrementmeaftertheotheroperators aredonewhereasprexhasanegoIamimportantsoincrementmerstandusemynewvalueforthe restoftheevaluations. 14.1.2.4AllowableDataTypes Withinsomeprogramminglanguages,incrementanddecrementcanbeusedonlyontheintegerdatatype. C++however,expandsthisnotonlytoalloftheintegerfamilybutalsototheoating-pointfamilyoat anddouble.Incrementing3.87willchangethevalueto4.87.Decrementing'C'willchangethevalueto'B'. RemembertheASCIIcharactervaluesarereallyonebyteunsignedintegersdomainfrom0to255. 14.1.2.5Exercises Exercise14.1 Solutiononp.182. Evaluatethefollowingitemsusingincrementordecrement: 1.Trueorfalse:x=x+1andx+=1andx++allaccomplishincrement? 2.Given:inty=19;andintz;whatvalueswillyandzhaveafter:z=y; 3.Given:doublex=7.77;andinty;whatvalueswillxandyhaveafter:y=++x; 4.Isthisok?Whyorwhynot?6*++age-3

PAGE 183

175 14.1.3Denitions Denition14.1:increment Addingonetothevalueofavariable. Denition14.2:decrement Subtractingonefromthevalueofavariable. Denition14.3:postx Placingtheincrementordecrementoperatortotherightoftheoperand. Denition14.4:prex Placingtheincrementordecrementoperatortotheleftoftheoperand. 14.2WhileLoop 2 14.2.1IntroductiontoTestBeforeLoops Therearetwocommonlyusedtestbeforeloopsintheiterationorrepetitioncategoryofcontrolstructures. Theyare:whileandfor.Thismodulecoversthe:while. 14.2.1.1UnderstandingIterationinGeneralwhile Theconceptofiterationisconnectedtopossiblywantingtorepeatanaction.Likeallcontrolstructureswe askaquestiontocontroltheexecutionoftheloop.Thetermloopcomesfromthecircularloopingmotion thatoccurswhenusingowcharting.Thebasicformofthewhileloopisasfollows: initializationoftheflag whiletheanswertothequestionistruethendo somestatementsoraction somestatementsoraction somestatementsoraction updatetheflag Inalmostalllanguagesthequestioncalleda testexpression isa Booleanexpression .TheBoolean datatypehastwovaluestrueandfalse.Let'srewritethestructuretoconsiderthis: initializationoftheflag whiletheexpressionistruethendo somestatementsoraction somestatementsoraction somestatementsoraction updatetheflag Withinthewhilecontrolstructuretherearefourattributestoaproperlyworkingloop.Theyare: Initializingtheag Textexpression Actionoractions Updateoftheag 2 Thiscontentisavailableonlineat.

PAGE 184

176 CHAPTER14.14.TESTBEFORELOOPS Theinitializationoftheagisnottechnicallypartofthecontrolstructure,butanecessaryitemtooccur beforetheloopisstarted.TheEnglishphrasingis,"Whiletheexpressionistrue,dothefollowingactions". Thisisloopingonthetrue.Whenthetestexpressionisfalse,youstoptheloopandgoonwiththenext itemintheprogram.Notice,becausethisisatestbeforelooptheaction mightnothappen .Itiscalled a testbeforeloop becausethetestcomesbeforetheaction.Itisalsosometimescalledapre-testloop, meaningthetestispreorLatinforbeforetheactionandupdate. 14.2.1.2HumanExampleofthewhileLoop Considerthefollowingone-wayconversationfromamothertoherchild. Child:Thechildsaysnothing,butmotherknowsthechildhadCheeriosforbreakfastandhistorytells usthatthechildmostlikelyspilledsomeCheeriosontheoor. Mothersays:"WhileitistruethatyouseeAslongasyoucanseeaCheerioonoor,pickitupand putitinthegarbage." Note:Alloftheelementsarepresenttodeterminetheactionorowthatthechildwillbedoingin thiscaserepeating.BecausethequestioncanyouseeaCheerioshasonlytwopossibleanswerstrueor falsetheactionwillcontinuewhilethereareCheeriosontheoor.Eitherthechild1neverpicksupa Cheeriobecausetheyneverspilledanyor2picksupaCheerioandkeepspickingupCheeriosoneatatime whilehecanseeaCheerioontheoorthatisuntiltheyareallpickedup. 14.2.2ThewhileStructurewithinC++ 14.2.2.1Syntax ThesyntaxforthedowhilecontrolstructurewithintheC++programminglanguageis: statement;//Thisstatementinitializestheflag; whileexpression { statement; statement; statement; statement;//Thisstatementupdatestheflag; } note: Thetestexpressioniswithintheparentheses,butthisisnotafunctioncall.Theparentheses arepartofthecontrolstructure.Additionally,thereisnotasemicolonaftertheparenthesis followingtheexpression. 14.2.2.2AnExample Example14.1:C++sourcecode:while loop_response='y'; whileloop_response=='y' { cout n nWhatisyourage?"; cin age_user; cout n nWhatisyourfriend'sage?";

PAGE 185

177 cin age_friend; cout n nTogetheryouragesaddupto:"; cout age_user+age_friend; cout n nDoyouwanttodoitagain?yorn"; cin loop_response; } Thefourattributesofatestbeforelooparepresent.Theinitializationoftheag.Thetestistheequality relationalcomparisonofthevalueintheagvariabletothelowercasecharacterofy.Theactionpart consistsofthe6linesthatpromptfordataandthendisplaysthetotalofthetwoages.Theupdateofthe agisthedisplayingthequestionandgettingtheanswerforthevariableloop_response. Thistypeofloopcontroliscalledaneventcontrolledloop.Theagupdatingisaneventwheresomeone decidesiftheywantthelooptoexecuteagain. Usingindentationwiththealignmentoftheloopactionsandagupdateisnormalindustrypractice withintheC++community. 14.2.2.3InniteLoops Atthispointit'sworthmentioningthatgoodprogrammingalwaysprovidesforamethodtoinsurethatthe loopquestionwilleventuallybefalsesothattheloopwillstopexecutingandtheprogramcontinueswith thenextlineofcode.However,ifthisdoesnothappenthentheprogramisinaninniteloop.Innite loopsareabadthing.Considerthefollowingcode: Example14.2:C++sourcecode:inniteloop loop_response='y'; whileloop_response=='y' { cout n nWhatisyourage?"; cin age_user; cout n nWhatisyourfriend'sage?"; cin age_friend; cout n nTogetheryouragesaddupto:"; cout age_user+age_friend; } Theprogrammerassignedavaluetotheagbeforetheloopwhichiscorrect.However,heforgottoupdate theag.Everytimethetestexpressionisaskeditwillalwaysbetrue.Thus,aninniteloopbecausethe programmerdidnotprovideawaytoexittheloopheforgottoupdatetheag.Considerthefollowing code: Example14.3:C++sourcecode:inniteloop loop_response='y'; whileloop_response='y' { cout n nWhatisyourage?"; cin age_user; cout n nWhatisyourfriend'sage?";

PAGE 186

178 CHAPTER14.14.TESTBEFORELOOPS cin age_friend; cout n nTogetheryouragesaddupto:"; cout age_user+age_friend; cout n nDoyouwanttodoitagain?yorn"; cin loop_response; } Nomatterwhattheuserrepliesduringtheagupdate,thetestexpressiondoesnotdoarelationalcomparison butdoesanassignment.Itassigns'y'tothevariableandasksif'y'istrue?Sinceallnon-zerovaluesare treatedasrepresentingtruewithintheBooleanconceptsoftheC++programminglanguage,theanswerto thetextquestionistrue.Viola,youhaveaninniteloop. 14.2.3CountingLoops Theexamplesaboveareforaneventcontrolledloop.Theagupdatingisaneventwheresomeonedecides iftheywantthelooptoexecuteagain.Oftentheinitializationsetstheagsothattheloopwillexecuteat leastonce. Anothercommonusageofthewhileloopisasacountingloop.Consider: Example14.4:C++sourcecode:whileloopthatiscounting counter=0; whilecounter < 5 { cout n nIloveicecream!"; counter++; } Thevariablecounterissaidtobecontrollingtheloop.Itissettozerocalledinitializationbeforeentering thewhileloopstructureandaslongasitislessthan5ve;theloopactionwillbeexecuted.Butpart oftheloopactionusestheincrementoperatortoincreasecounter'svaluebyone.Afterexecutingtheloop vetimesonceforcounter'svaluesof:0,1,2,3and4theexpressionwillbefalseandthenextlineof codeintheprogramwillexecute.Acountingloopisdesignedtoexecutetheactionwhichcouldbemore thanonestatementasetofgivennumberoftimes.Inourexample,themessageisdisplayedvetimeson themonitor.Itisaccomplishedmymakingsureallfourattributesofthewhilecontrolstructurearepresent andworkingproperly.Theattributesare: Initializingtheag Textexpression Actionoractions Updateoftheag Missinganattributemightcauseaninnitelooporgiveundesiredresultsdoesnotworkproperly. 14.2.3.1InniteLoops Consider: Example14.5:C++sourcecode:inniteloop

PAGE 187

179 counter=0; whilecounter < 5 { cout n nIloveicecream!"; } Missingtheagupdateusuallycausesaninniteloop. 14.2.3.2VariationsonCounting Inthefollowingexample,theintegervariableageissaidtobecontrollingtheloopthatistheag.Wecan assumethatagehasavalueprovidedearlierintheprogram.Becausethewhilestructureisatestbefore loop;itispossiblethattheperson'sageis0zeroandthersttimewetesttheexpressionitwillbefalse andtheactionpartoftheloopwouldneverbeexecuted. Example14.6:C++sourcecode:whileasacountingloop while < age { cout n nIlovecandy!"; age--; } Considerthefollowingvariationassumingthatageandcounterarebothintegerdatatypeandthatagehas avalue: Example14.7:C++sourcecode:whileasacountingloop counter=0; whilecounter < age { cout n nIlovecornchips!"; counter++; } Thisloopisacountingloopsimilartoourrstcountingloopexample.Theonlydierenceisinsteadof usingaliteralconstantinotherwords5inourexpression,weusedthevariableageandthusthevalue storedinagetodeterminehowmanytimestoexecutetheloop.However,unlikeourrstcountingloop examplewhichwillalwaysexecuteexactly5times;itispossiblethattheperson'sageis0zeroandthe rsttimewetesttheexpressionitwillbefalseandtheactionpartoftheloopwouldneverbeexecuted. 14.2.4Denitions Denition14.5:while AtestbeforeiterationcontrolstructureavailableinC++. Denition14.6:loopattributes Itemsassociatedwithiterationorloopingcontrolstructures.

PAGE 188

180 CHAPTER14.14.TESTBEFORELOOPS Denition14.7:initializeitem Anattributeofiterationcontrolstructures. Denition14.8:mightnothappen Indicatingthattestbeforeloopsmightnotexecutetheaction. Denition14.9:eventcontrolled Usinguserinputtocontrolaloop. Denition14.10:countingcontrolled Usingavariabletocountupordowntocontrolaloop. 14.3Practice14:TestBeforeLoops 3 14.3.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Identifywhichselectioncontrolstructuresaretestbeforeiteration. 3.Beabletowritepseudocodeorowchartingforthewhilecontrolstructure. 4.BeabletowriteC++sourcecodeforthewhilecontrolstructure. 14.3.2MemoryBuildingActivities Linkto:MBA14 4 14.3.3Exercises Exercise14.2 Solutiononp.182. Evaluatethefollowingitemsusingincrementordecrement: 1.Trueorfalse: x=x-1; and x-=1; and x; and x; allaccomplishdecrement. 2.Given: inty=26; and intz; whatvalueswillyandzhaveafter: z=y++; 3.Given: doublex=4.44; and inty; whatvalueswillxandyhaveafter: y=x; 4.Asanexpression: 10/++money*4 Isthisok?Whyorwhynot? 14.3.4MiscellaneousItems Linkto:Animatedgifshowingawhileloop 5 3 Thiscontentisavailableonlineat. 4 Seetheleat 5 Seetheleat

PAGE 189

181 14.3.5LabAssignment 14.3.5.1CreatingaFolderorSub-FolderforChapter14Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_14withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 14.3.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_14_Pseudocode.txt 6 14.3.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefromtheLab_14_Pseudocode.txtle.Nameit:Lab_14.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 14.3.6Problems 14.3.6.1Problem14aInstructions Flowchartthefollowingpseudocode: Example14.8:pseudocode Assigncounteravalueofzero Whilecounterislessthan5 Display"Ilovecookies!" Incrementcounter Endwhile 6 Seetheleat

PAGE 190

182 CHAPTER14.14.TESTBEFORELOOPS SolutionstoExercisesinChapter14 SolutiontoExercise14.1p.174 Answers: 1.true 2.yis:18andzis:19 3.xis:8.77andyis:8Note:truncationof8.77to8upondemotion. 4.Notok.Error,theitemincrementedmusthaveLvalueattributes,usuallyavariable.Itisanexpression notavariable. SolutiontoExercise14.2p.180 Answers: 1.true 2.yis:27andzis:26 3.xis:3.44andyis:3Note:truncationof3.44to3upondemotiontointegerdatatype. 4.Notok.Error,theitemincrementedmusthaveLvalueattributes,usuallyavariable.Becauseofthe parentheses,itisanexpressionnotavariable.

PAGE 191

Chapter15 15.CountingLoops 15.1ForLoop 1 15.1.1IntroductiontoTestBeforeLoops Therearetwocommonlyusedtestbeforeloopsintheiterationorrepetitioncategoryofcontrolstructures. Theyare:whileandfor.Thismodulecoversthe:for. 15.1.1.1UnderstandingIterationinGeneralfor Inmostprogramminglanguagestheforloopisusedexclusivelyforcounting;thatistorepeataloopactionas iteithercountsuporcountsdown.Thereisastartingvalueandastoppingvalue.Thequestionthatcontrols theloopisa testexpression thatcomparesthestartingvaluetothestoppingvalue.Thisexpressionis aBooleanexpressionandisusuallyusingtherelationaloperatorsofeitherlessthanforcountingupor greaterthanforcountingdown.Thetermloopcomesfromthecircularloopingmotionthatoccurswhen usingowcharting.Thebasicformoftheforloopcountingupisasfollows: for initializationofthestartingvalue startingvalueislessthanthestoppingvalue somestatementsoraction somestatementsoraction somestatementsoraction incrementthestartingvalue Itmightbebesttounderstandtheforloopbyunderstandingawhileloopactinglikeacountingloop. Let'sconsider; initializationofthestartingvalue whilethestartingvalueislessthanthestoppingvalue somestatementsoraction somestatementsoraction somestatementsoraction incrementthestartingvalue 1 Thiscontentisavailableonlineat. 183

PAGE 192

184 CHAPTER15.15.COUNTINGLOOPS Withintheforcontrolstructuretherearefourattributestoaproperlyworkingloop.Theyare: Initializingtheagdoneonce Textexpression Actionoractions Updateoftheag Theinitializationoftheagisnottechnicallypartofthewhilecontrolstructure,butitisusuallypartofthe forcontrolstructure.TheEnglishphrasingis,"Forxis1;xlessthan3;dothefollowingactions;increment x;loopbacktothetestexpression".Thisisdoingtheactiononthetrue.Whenthetestexpressionisfalse, youstoptheloopandgoonwiththenextitemintheprogram.Notice,becausethisisatestbeforeloop theaction mightnothappen .Itiscalleda testbeforeloop becausethetestcomesbeforetheaction.It isalsosometimescalledapre-testloop,meaningthetestispreorLatinforbeforetheactionandupdate. 15.1.2TheforStructurewithinC++ 15.1.2.1Syntax ThesyntaxforthedowhilecontrolstructurewithintheC++programminglanguageis: forinitializations;expression;updates { statement; statement; statement; } note: Theinitializations,testexpressionandupdatesarewithintheparentheseseachseparated byasemi-colon,butthisisnotafunctioncall.Theparenthesesarepartofthecontrolstructure. Additionally,thereisnotasemicolonaftertheparenthesisfollowingtheexpression. 15.1.2.2AnExample Example15.1:C++sourcecode:for forcounter=0;counter < 5;counter++ { cout n nIloveicecream!"; } Thefourattributesofatestbeforelooparepresent.Theinitializationoftheag.Thetestisthelessthan relationalcomparisonofthevalueintheagvariabletotheconstantvalueof5.Theactionpartconsistsof the1lineofoutput.Theupdateoftheagisdonewiththeincrementoperator. UsingindentationwiththealignmentoftheloopactionsisnormalindustrypracticewithintheC++ community.

PAGE 193

185 15.1.2.3InniteLoops Atthispointit'sworthmentioningthatgoodprogrammingalwaysprovidesforamethodtoinsurethatthe loopquestionwilleventuallybefalsesothattheloopwillstopexecutingandtheprogramcontinueswith thenextlineofcode.However,ifthisdoesnothappenthentheprogramisinaninniteloop.Inniteloops areabadthing.Considerthefollowingcode: Example15.2:C++sourcecode:inniteloop forcounter=0;counter < 5; { cout n nIloveicecream!"; } Theprogrammerassignedavaluetotheagduringtheinitializationstepwhichiscorrect.However,he forgottoupdatetheagtheupdatestepismissing.Everytimethetestexpressionisaskeditwillalways betrue.Thus,aninniteloopbecausetheprogrammerdidnotprovideawaytoexittheloopheforgotto updatetheag. 15.1.2.4MultipleItemsintheInitializationandUpdate Thefollowingshowstheuseofthesequenceoperatortoseparatethemultipleinitializationsandmultiple updates.Thisisnotavailableinmostlanguages,thusismoreuniquetotheC++programminglanguage. Example15.3:C++sourcecode:forwithmultipleinitializationsandupdates forx=0,y=10;x < 10;x++,y-{ cout x*y endl; } 15.1.3CountingLoopConversionawhileintoafor Belowisacolorcodedtheconversionofawhileloopthatdisplaysamessageexactlythreetimeswhichisa countingloopintoaforloopusingC++programminglanguagesyntax.Thefourloopattributesarecolor highlightedasfollows:

PAGE 194

186 CHAPTER15.15.COUNTINGLOOPS Figure15.1 15.1.4MiscellaneousInformationabouttheforStructure ManylanguagesPascal,FORTRAN,andotherhaveaforloopstructurethatisusedexclusivelyfor counting.TheforloopintheC++programminglanguageismuchmoreversatileandcanbeusedand generallyisusedinplaceofthewhileloopstructure.Inrealityacountingloopisjustaparticularuseofa whileloop. Thenameforcomesfrommathematics'methodofwritinganiterationorrepetition.Inmathwewould say:Forthevariableistartsatagivenvalueandrepeatsanactionincreasingthevalueofiuntiliis executedforthestoppingvalue.Usuallywritteninmathas: fori=1to5dosomeaction Note:herethe=meansequalsnotassignment.Anotherwaytosayitisthativariesfrom1to5. 15.1.5Denitions Denition15.1:for Atestbeforeiterationcontrolstructuretypicallyusedforcounting.

PAGE 195

187 15.2CircularNatureoftheIntegerDataTypeFamily 2 15.2.1GeneralDiscussion Therearetimeswhencharacterandintegerdatatypesarelumpedtogetherbecausetheybothactthesame oftencalledtheintegerfamily.Maybeweshouldsaytheyactdierentlythantheoating-pointdatatypes. Theintegerfamilyvaluesjumpfromonevaluetoanother.Thereisnothingbetween6and7norbetween'A' and'B'.Itcouldbeaskedwhynotmakeallyournumbersoating-pointdatatypes.Thereasonistwofold. First,somethingsintherealworldarenotfractional.Adog,evenwithonly3legs,isstillonedognotthree fourthsofadog.Second,theintegerdatatypeisoftenusedtocontrolprogramowbycountingcounting loops.Theintegerfamilyhasacircularwraparoundfeature.Usingatwobyteinteger,thenextnumber biggerthan32767isnegative32768characteractsthesamewaygoingfrom255to0.Wecouldalsoreverse thattobethenextsmallernumberthannegative32768ispositive32767.Thiscanbeshownbyusinga normalmathline,limitingthedomainandthenconnectingthetwoendstoformacircle. Figure15.2 Thiscircularnatureoftheintegerfamilyworksforbothintegerandcharacterdatatypes.Intheory,it 2 Thiscontentisavailableonlineat.

PAGE 196

188 CHAPTER15.15.COUNTINGLOOPS shouldworkfortheBooleandatatypeaswell;butinmostprogramminglanguagesitdoesnotforvarious technicalreasons. "Inmathematics,modulararithmeticsometimescalledclockarithmeticisasystemofarithmeticfor integerswherenumbers"wraparound"aftertheyreachacertainvaluethemodulus. ::: Afamiliaruseofmodulararithmeticisitsuseinthe12hourclockthearithmeticoftime-keepingin whichthedayisdividedintotwo12hourperiods.Ifthetimeis7:00now,then8hourslateritwillbe 3:00.Usualadditionwouldsuggestthatthelatertimeshouldbe7+8=15,butthisisnottheanswer becauseclocktime"wrapsaround"every12hours;thereisno"15o'clock".Likewise,iftheclockstartsat 12:00noonand21hourselapse,thenthetimewillbe9:00thenextday,ratherthan33:00.Sincethehour numberstartsoverwhenitreaches12,thisisarithmeticmodulo12. Figure15.3 Time-keepingonaclockgivesanexampleofmodulararithmetic."ModulararithmeticfromWikipedia Theuseofthemodulusoperatorinintegerdivisionistiedtotheconceptsusedinmodulararithmetic. 15.2.2ImplicationsWhenExecutingLoops Ifaprogrammersetsupacountingloopincorrectly,usuallyoneofthreethingshappen: Inniteloopusuallycausedbymissingupdateattribute. Loopneverexecutesusuallythetextexpressioniswrongwiththedirectionofthelessthanorgreater thanrelationshipneedingtobeswitched. Loopexecutesmoretimesthandesiredupdatenotproperlyhandled.Usuallythedirectionofcounting incrementordecrementneedtobeswitched. Let'sgiveanexampleoftheloopexecutingforwhatappearstobeforinnitythethirditemonourlist. Example15.4:C++sourcecode forintx=0;x < 10;x-{ cout x endl; } Theabovecodeaccidentlydecrementsandthevalueofxgoesinanegativewaytowards-2147483648the largestnegativevalueinanormalfourbytesignedintegerdatatype.Itmighttakeawhilethusitmight appeartobeinaninniteloopforittoreachthenegative2billionplusvalue,beforenallydecrementing topositive2147483647whichwould,incidentally,stoptheloopexecution.

PAGE 197

189 15.2.3DemonstrationPrograminC++ 15.2.3.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 15.2.3.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Circular_Nature_Integer.cpp 3 15.2.4Denitions Denition15.2:circularnature Connectingthenegativeandpositiveendsofthedomainofanintegerfamilydatatype. Denition15.3:loopcontrol Makingsuretheattributesofaloopareproperlyhandled. Denition15.4:modulararithmetic Asystemofarithmeticforintegerswherenumbers"wraparound". 15.3FormattingOutput 4 15.3.1GeneralDiscussion Formattingofoutputishandledindierentwaysinthevariouslanguagesusedtoday.Manyprogramming languageshavedierentformattinginstructionsforthestandardoutputdevicewhichisusuallythemonitor goingtoaDOSblackscreenoutputboxversususingthemonitorasaGraphicalUserInterfaceGUI. Filestorageoutputisoftenhandledsimilarlytothestandardoutputdevice.Allofthismakesformatting ofoutputverymachine,outputdeviceandlanguagedependent. Whenteachingprogrammingfundamentals,manyprofessorsprefertousethestandardoutputdevice. FortheC++programminglanguagethismeansgoingtothemonitorusingaDOSblackscreenoutputbox. 15.3.2C++ConsiderationsusingStandardOutputcout 15.3.2.1TextWrappingandVerticalSpacing Therearetwoitemsusedtokeepoutputfromllingupalineand wrapping ontothenextline.Theyare: Usingtheescapecodesequenceof n nwithinyourstringstextbetweenassetofdoublequotemarks. Usingtheitemfromtheiostreamnamed:endl;whichisshortforendline. Thustheprogrammerisresponsibleformakingtextshowreasonablyonthescreen.Bothoftheabovealso allowforadequate verticalspacing whenneededinyouroutput. 3 Seetheleat 4 Thiscontentisavailableonlineat.

PAGE 198

190 CHAPTER15.15.COUNTINGLOOPS 15.3.2.2HandlingFloating-pointDataType Itisnicetohaveyouroutputdisplayedsohumanscanreaditmosthumansarenotusetoscientic notation.Therearethreelinesofteninsertednearthestartofyourcoderstitemsinthefunctionmain thatcanbeusedtodirecttheformattingofoating-pointdata.Theyare: cout.setfios::fixed; cout.setfios::showpoint; cout.precisionn; Theydothefollowingfortherestofyourprogram: xedDonotusescienticnotationbutshowoating-pointvalueslikeintegervaluesnumeraldigits of0to9noexponentnotation. showpointAlwaysshowadecimalpointforoating-pointvaluesevenifthereisnofractionalpart. precisionAlwaysshowthisnumberofdigitschangentoanumberlike2totherightofthedecimal point. 15.3.2.3SettingtheWidthforNumbers Settingthewidthforintegerfamilyandoating-pointfamilydatatypesmustbedonefortheoutputofeach value.Assumeinthefollowingexamplethatageisanintegerdatatypeandmoneyisaoating-pointdata type. cout setw age endl; cout setw money endl; Notethateachvaluehadtohaveitsownsetwnwherenisanintegernumbertellingithowmany positionstousefortheoutput.Theiomanipheaderleimmediatelyshownwillneedtobeincludedin yourprogram. #include < iomanip > //neededforthesetw 15.3.3DemonstrationPrograminC++ 15.3.3.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 15.3.3.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Formatting_Output.cpp 5 15.3.4Denitions Denition15.5:formatting Modifyingthewaytheoutputisdisplayed. Denition15.6:wrapping Whenoutputisnotverticallyspacedproperly. 5 Seetheleat

PAGE 199

191 15.4NestedForLoops 6 15.4.1GeneralDiscussion 15.4.1.1NestedControlStructures Wearegoingtorstintroducetheconceptofnestedcontrolstructures.Nestingisaconceptthatplacesone iteminsideofanother.Consider: ifexpression trueaction else falseaction Thisisthebasicformoftheifthenelsecontrolstructure.Nowconsider: ifageislessthan18 youcan'tvote ifageislessthan16 youcan'tdrive else youcandrive else youcanvote ifageislessthan21 youcan'tdrink else youcandrink Asyoucanseewesimplyincludedaspartofthe"trueaction"astatementandanotherifthenelse controlstructure.Wedidthesamenestedanotherifthenelseforthe"falseaction".Inourexamplewe nestedifthenelsecontrolstructures.Nestingcouldhaveanifthenelsewithinawhileloop.Thus,the conceptofnestingallowsthemixingofthedierentcategoriesofcontrolstructures. Manycomplexlogicproblemsrequireusingnestedcontrolstructures.Bynestingcontrolstructuresor placingoneinsideanotherwecanaccomplishalmostany complexlogic problem. 15.4.2AnExampleNestedforloops Hereisanexampleofa12by12multiplicationtable: 1|2|3|4|5|6|7|8|9|10|11|12| ------------------------------------------------------------------------1!1|2|3|4|5|6|7|8|9|10|11|12| 2!2|4|6|8|10|12|14|16|18|20|22|24| 3!3|6|9|12|15|18|21|24|27|30|33|36| 4!4|8|12|16|20|24|28|32|36|40|44|48| 5!5|10|15|20|25|30|35|40|45|50|55|60| 6!6|12|18|24|30|36|42|48|54|60|66|72| 7!7|14|21|28|35|42|49|56|63|70|77|84| 6 Thiscontentisavailableonlineat.

PAGE 200

192 CHAPTER15.15.COUNTINGLOOPS 8!8|16|24|32|40|48|56|64|72|80|88|96| 9!9|18|27|36|45|54|63|72|81|90|99|108| 10!10|20|30|40|50|60|70|80|90|100|110|120| 11!11|22|33|44|55|66|77|88|99|110|121|132| 12!12|24|36|48|60|72|84|96|108|120|132|144| Wemightalsoseethattheanswerscouldbedesignedasacollectionofcellseachcellbeingexactlysix spaceswide.TheC++sourcecodetoproducetheaboveis: Example15.5:C++sourcecode:nestedforloops-multiplicationtable cout ""; foracross=1;across < 13;across++ { cout setw across "|"; } cout endl; cout ""; foracross=1;across < 13;across++ { cout "------"; } cout endl; fordown=1;down < 13;down++ { cout setw down "!"; foracross=1;across < 13;across++ { cout setw down*across "|"; } cout endl; }

PAGE 201

193 Figure15.4: ColorizedCode-multiplicationtable

PAGE 202

194 CHAPTER15.15.COUNTINGLOOPS Figure15.5: ColorizedOutput-multiplicationtable 15.4.3DemonstrationPrograminC++ 15.4.3.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 15.4.3.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Nested_For_Loops.cpp 7 7 Seetheleat

PAGE 203

195 15.4.4Denitions Denition15.7:complexlogic Oftensolvedwithnestedcontrolstructures. 15.5Practice15:CountingLoops 8 15.5.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Identifywhichselectioncontrolstructuresarecommonlyusedacountingloops. 3.Beabletowritepseudocodeorowchartingfortheforcontrolstructure. 4.BeabletowriteC++sourcecodeforaforcontrolstructure. 5.Whenfeasible,beabletoconvertC++sourcecodefromwhileloopactinglikeacountinglooptoa forloopandandviceversa. 15.5.2MemoryBuildingActivities Linkto:MBA15 9 15.5.3Exercises Exercise15.1 Solutiononp.197. Answerthefollowingstatementsaseithertrueorfalse: 1.Onlyforloopscanbecountingloops. 2.Theintegerdatatypehasmodulararithmeticattributes. 3.Theescapecodeof n nispartofformattingoutput. 4.NestedforloopsisnotallowedintheC++programminglanguage. 5.Countingloopsuseallfouroftheloopattributes. 15.5.4MiscellaneousItems Noneatthistime. 15.5.5LabAssignment 15.5.5.1CreatingaFolderorSub-FolderforChapter15Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_15withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 8 Thiscontentisavailableonlineat. 9 Seetheleat

PAGE 204

196 CHAPTER15.15.COUNTINGLOOPS 15.5.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_15a.cpp 10 15.5.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CompileandruntheLab_15a.cppsourcecodele.Understandhowitworks. CopythesourcecodeleLab_15a.cppnamingit:Lab_15b.cpp Convertthecodethatiscountingallfourattributestoaforloop. Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 15.5.6Problems 15.5.6.1Problem15aInstructions UsingproperC++syntax,convertthefollowingforlooptoawhileloop. Example15.6:C++sourcecode forx=0;x < 10;x++ { cout "Havingfun!"; } 10 Seetheleat

PAGE 205

197 SolutionstoExercisesinChapter15 SolutiontoExercise15.1p.195 Answers: 1.false 2.true 3.true 4.false 5.true

PAGE 206

198 CHAPTER15.15.COUNTINGLOOPS

PAGE 207

Chapter16 16.StringClass,UnaryPositiveand Negative 16.1StringClasswithinC++ 1 16.1.1GeneralDiscussion Inmostprogramminglanguagesastringistypicallyastringofcharactersstringthemalonginaseries. Therulesforhandlingstringsvaryfromlanguagetolanguage.Technically,thereisnostringdatatypein theC++programminglanguage.However,theconceptofastringdatatypemakesiteasytohandlestings ofcharacterdata.AssociatedwithobjectorientedprogrammingthestringclasshasbeenaddedtoC++as astandardpartoftheprogramminglanguage. Mostdataismorecomplexthanjustonecharacter,integer,etc.Programminglanguagesdevelopother methodstorepresentandstoredatathataremorecomplex.Acomplexdatatypeofarrayisrstmost studentsencounter.Anarrayisasequencedcollectionofelementsofthesamedatatypewithasingle identiername.Thisdenitionperfectlydescribesourstringdatatypeconcept.Thesimplestarrayis calledaone-dimensionalarray;alsoknowasalistbecauseweusuallylistthemembersorelementsvertically.However,stringsareviewedasaone-dimensionalarraythatvisualizeaslistedhorizontally.Strings areanarrayofcharacterdata. Inthe"C"programminglanguageallstringswerehandledasanarrayofcharactersthatendinanASCII nullcharacterthevalue0ortherstcharacterinthe ASCII charactercodeset.Thischangedwiththe implementationofthestringclasswithinC++wherestringsarestoredasalengthcontrolledarraywitha maximumlengthof255characters.Thisstringclassimplementationalsoallowedprogrammerstousethe reservedword string asifitwereadatatype.Commonlyusedoperatorsandsomealternativesforthe stringclassaresummarizedinthefollowingtable: C++Operator OperatorName StringClassImplementation = assignment Sameasforstandarddatatypes < > < =, > =,==,!= sixrelational Sameasforstandarddatatypes continuedonnextpage 1 Thiscontentisavailableonlineat. 199

PAGE 208

200 CHAPTER16.16.STRINGCLASS,UNARYPOSITIVEANDNEGATIVE + addition ConcatenationorAppend sizeof Usagehowmanybytesadata typeoccupies Implementedusingaclassmemberfunctionnamedlength.Format:identier_name.length NOTE:Theperiodbetweenthe identiernameandthefunction nameistheclassmemberoperator. theperiod classmember Usedinconjunctionwithclass functions Table16.1 Mostotheroperatorsarenotallowedandbasicallydonotmakesenseforastringdatatype.Theabove itemsaredemonstratedinthefollowingprogram. 16.1.2DemonstrationPrograminC++ 16.1.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 16.1.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_String_Class.cpp 2 16.1.3Denitions Denition16.1:array Asequencedcollectionofelementsofthesamedatatypewithasingleidentiername. Denition16.2:concatenation Combiningtwostringsintoonestring. Denition16.3:stringclass Acomplexdataitemthatusesobjectorientedprogramming. Denition16.4:classmember Anoperatorusedtoinvokefunctionsassociatedwithaclass. 2 Seetheleat

PAGE 209

201 16.2UnaryPositiveandNegativeOperators 3 16.2.1GeneralDiscussion Unarypositivealsoknownasplusandunarynegativealsoknownasminusareuniqueoperators.Theplus andminuswhenusedwithaconstantvaluerepresenttheconceptthatthevaluesareeitherpositiveor negative.Let'sconsider: +5+-2 Wehavethreeoperatorsinthisorder:unarypositive,addition,andunarynegative.Theanswerto thisexpressionisapositive3.Asyoucansee,onemustdierentiatebetweenwhentheplussignmeans unarypositiveandwhenitmeansaddition.Unarynegativeandsubtractionhavethesameproblem.Let's consider: -2-+5 Theexpressionevaluatestonegative7.Let'sconsider: 7--2 Firstconstantsthatdonothaveaunaryminisinfrontofthemareassumedthedefaulttobepositive. Whenyousubtractanegativenumberitislikeadding,thustheexpressionevaluatestopositive9. 16.2.2C++CodeExamples TheaboveexamplesworkwithintheC++programminglanguage.Whathappensifweputaunarypositive orunarynegativeinfrontofavariableoranamedconstant? 16.2.2.1NegationUnaryNegative Theconceptofnegationistotakeavalueandchangeitssign,thatis:ipit.Ifitpositivemakeitnegative andifitisnegativemakeitpositive.Mathematically,itisthefollowingC++codeexample,giventhat moneyisanintegervariablewithavalueof6: -money money*-1 Theabovetwoexpressionsevaluatetothesamevalue.Intherstline,thevalueinthevariablemoney isfetchedandthenit'snegatedtoanegative6.Inthesecondline,thevalueinthevariablemoneyisfetched andthenit'smultipliedbynegative1makingtheansweranegative6. 16.2.2.2UnaryPositiveWorthless Simplytosatisfysymmetry,theunarypositivewasaddedtotheC++programminglanguageasonoperator. However,itisatotallyworthlessoruselessoperatorandisrarelyused.Howeverdon'tbeconfusedthe followingexpressioniscompletelyvalid: 6++5 Thesecond+signisinterpretedasunarypositive.Therst+signisinterpretedasaddition. money +money money*+1 Forallthreelines,ifthevaluestoredinmoneyis6thevalueoftheexpressionis6.Evenifthevalue inmoneywasnegative77thevalueoftheexpressionwouldbenegative77.Theoperatordoesnothing, becausemultiplyinganythingby1doesnotchangeitsvalue. 3 Thiscontentisavailableonlineat.

PAGE 210

202 CHAPTER16.16.STRINGCLASS,UNARYPOSITIVEANDNEGATIVE 16.2.2.3PossibleConfusion Donotconfusetheunarynegativeoperatorwithdecrement.Decrementchangesthevalueinthevariable andthusisanLvalueconcept.Unarynegativedoesnotchangethevalueofthevariable,butusesitinan Rvaluecontext.Itfetchesthevalueandthennegatesthatvalue.Theoriginalvalueinthevariabledoesnot change. Becausethereisnochangingofthevalueassociatedwiththeidentiername,theidentiernamecould representavariableornamedconstant. 16.2.2.4Exercises Exercise16.1 Solutiononp.205. Evaluatethefollowingitemsinvolvingunarypositiveandunarynegative: 1.+10--2 2.-18+24 3.4-+3 4.+8+-+5 5.+8+/+5 16.2.3Denitions Denition16.5:unarypositive Aworthlessoperatoralmostneverused. Denition16.6:unarynegative Anoperatorthatcausesnegation. Denition16.7:plus Akaunarypositive. Denition16.8:minus Akaunarynegative. 16.3Practice16:StringClass,UnaryPostitiveandNegative 4 16.3.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Identifywhichoperatorsareallowedwiththestringclass. 3.Understandtheunarypositiveandunarynegativeoperators. 16.3.2MemoryBuildingActivities Linkto:MBA16 5 4 Thiscontentisavailableonlineat. 5 Seetheleat

PAGE 211

203 16.3.3Exercises Exercise16.2 Solutiononp.205. Evaluatethefollowingitemsinvolvingunarypositiveandunarynegative: 1.+13--2 2.-10+14 3.4+-3 4.+8-*+5 16.3.4MiscellaneousItems Noneatthistime. 16.3.5LabAssignment 16.3.5.1CreatingaFolderorSub-FolderforChapter16Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_16withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 16.3.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_16_Pseudocode.txt 6 16.3.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefromtheLab_16_Pseudocode.txtle.Nameit:Lab_16.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 16.3.6Problems 16.3.6.1Problem16aInstructions DescribethenormalC++operatorsallowedwiththestringdatatype. 16.3.6.2Problem16bInstructions Describewhyunarypositiveisworthless. 6 Seetheleat

PAGE 212

204 CHAPTER16.16.STRINGCLASS,UNARYPOSITIVEANDNEGATIVE 16.3.6.3Problem16cInstructions Describehowunarynegativeworks.

PAGE 213

205 SolutionstoExercisesinChapter16 SolutiontoExercise16.1p.202 Answers: 1.12 2.6 3.1 4.It's3.Surprised,butitworks.Themiddleplussignisadditionandtherestareunarypositiveor unarynegative. 5.Error,nooperandbetweenadditionanddivision. SolutiontoExercise16.2p.203 Answers: 1.15 2.4 3.1 4.Error,nooperandbetweensubtractionandmultiplication.

PAGE 214

206 CHAPTER16.16.STRINGCLASS,UNARYPOSITIVEANDNEGATIVE

PAGE 215

Chapter17 17.ConditionalOperatorandRecursion 17.1ConditionalOperator 1 17.1.1Overview Theconditionaloperatorisuniqueinthatithasthreeoperandsseparatedbytwounconnectedoperator symbols.AllotherC++operatorsareeitherunaryoneoperatorandoneoperandorbinaryoneoperator andtwooperands.Onthe"AbbreviatedPrecedenceChartforC++Operators"theconditionaloperator hastheword"trinary"inthecommentscolumn.Thisprex"tri"meansthree,thusthreeoperands. C++Operator Meaning Comments ?: conditional trinarythreeoperandswithtwooperators Table17.1 Asanoperatoritproducesavaluefortheexpression.Aneasywaytoexplaintheconditionaloperator istoconvertan"ifthenelse"controlstructuretoanexpressionusingtheconditionaloperator. Example17.1:ifthenelse ifage > 17 { cout "Youcanvote."; } else { cout "Youcan'tvote."; } Example17.2:conditional=option1 age > 17?cout "Youcanvote.":cout "Youcan'tvote."; 1 Thiscontentisavailableonlineat. 207

PAGE 216

208 CHAPTER17.17.CONDITIONALOPERATORANDRECURSION Example17.3:conditional=option2 cout age > 17?"Youcanvote.":"Youcan'tvote."; note: Theuseofparenthesizesisneededbecauseoftheprecedenceofoperators.Theconditional expressionisoflowerprecedencethantheinsertionwritingoperator. Therstoperandisa testexpression similartothosethatcontrolprogramowincontrolstructures. Thistypeofexpressionisalsoknownasa Booleanexpression becausetheycreateaBooleananswerof trueorfalse.Ifthetestistruethesecondoperandbecomesthevalueoftheexpression.Iffalse,thethird operandbecomesthevalueoftheexpression.Theoperatorsofthequestionmarkandcolonseparatethe threeoperands. Example17.4:generalformat testexpression?expressiontrue:expressionfalse 17.1.2Denitions Denition17.1:conditional AtrinaryC++operatorthatactslikeanifthenelsecontrolstructure. 17.2RecursionvsIteration 2 17.2.1RepetitiveAlgorithms "Ingeneral,therearetwoapproachestowritingrepetitivealgorithms.Oneusesloops;theotheruses recursion. Recursion isarepetitiveprocessinwhichafunctioncallsitself.Bothapproachesprovide repetition,andeithercanbeconvertedtotheother'sapproach." 3 Iterationisoneofthecategoriesofcontrol structures.Itallowsfortheprocessingofsomeactionzerotomanytimes.Iterationisalsoknownas loopingandrepetition.Themathterm"toiterate"meanstoperformthestatementpartsoftheloop.Many problems/tasksrequiretheuseofrepetitivealgorithms.Withmostprogramminglanguagesthiscanbe donewitheither: 1.loopingcontrolstructures,specicallytheforloopaniterativeapproach 2.recursivecallingofafunction Usingrepetitivealgorithmsasthesolutionmethodoccursinmanymathematicalorientedproblems.These inincludefactorial,Fibonaccinumbers,andtheTowersofHanoiproblem.Solutionstotheseproblems areoftenonlypresentedintermsofusingtherecursivemethod.However," ::: youshouldunderstandthe twomajorlimitationsofrecursion.First,recursivesolutionsmayinvolveextensiveoverheadbecausethey usefunctioncalls.Second,eachtimeyoumakeacallyouuseupsomeofyourmemoryallocation.Ifthe 2 Thiscontentisavailableonlineat. 3 BehrouzA.ForouzanandRichardF.Gilberg, Computer Science A Structured Approach using C++ Second EditionUnited StatesofAmerica:ThompsonBrooks/Cole,2004265.

PAGE 217

209 recursionisdeepthatis,ifthereisalargenumberorrecursivecallsthenyoumayrunoutofmemory. BoththefactorialandFibonaccinumberssolutionsarebetterdevelopediteratively." 4 Understandinghowrecursionortheiterativeapproachesworkwillbelefttoothers.Theyareusually coveredindetailaspartofstudyingdatastructures.Ourgoalincoveringthemisto: 1.Provideyouwithadenitionofrecursion 2.Introducethealternatesolutionapproachofiteration Thefollowingdemonstrationprogramshowsbothsolutionsfor8!eightfactorial. 17.2.2DemonstrationPrograminC++ 17.2.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 17.2.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Factorial.cpp 5 17.2.3Denitions Denition17.2:recursion Arepetitiveprocessinwhichafunctioncallsitself. Denition17.3:factorial Amathproblemthatoftenissolvedusingrecursion. 17.3Practice17:ConditionalOperatorandRecursion 6 17.3.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Understandtheconditionaloperatorandhowitworks. 3.Understandrecursionasaproblemsolvingtechnique. 4.Whenfeasible,beabletoconvertC++sourcecodefromaconditionalexpressiontoanifthenelse andviceversa. 4 BehrouzA.ForouzanandRichardF.Gilberg, Computer Science A Structured Approach using C++ Second EditionUnited StatesofAmerica:ThompsonBrooks/Cole,2004272. 5 Seetheleat 6 Thiscontentisavailableonlineat.

PAGE 218

210 CHAPTER17.17.CONDITIONALOPERATORANDRECURSION 17.3.2MemoryBuildingActivities Linkto:MBA17 7 17.3.3Exercises Exercise17.1 Solutiononp.212. Answerthefollowingstatementsaseithertrueorfalse: 1.Theconditionalexpressionactslikeacasestructure. 2.Theconditionaloperatorisatwopartoperatorwiththreeoperands. 3.Recursionisonemethodofimplementingarepetitivealgorithm. 4.Recursionisalwayspreferredoveraniterativeapproachtoarepetitiveproblem. 5.Factorialisusuallydemonstratedwithaniterativeapproach. 17.3.4MiscellaneousItems Noneatthistime. 17.3.5LabAssignment 17.3.5.1CreatingaFolderorSub-FolderforChapter17Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_17withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 17.3.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_17a.cpp 8 17.3.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CompileandruntheLab_17a.cppsourcecodele.Understandhowitworks. CopythesourcecodeleLab_17a.cppnamingit:Lab_17b.cpp Convertthecodethatisusingtheifthenelsetoaconditionalexpression. Convertthecodethatisusingtheconditionalexpressiontoanifthenelse. Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 7 Seetheleat 8 Seetheleat

PAGE 219

211 17.3.6Problems 17.3.6.1Problem17aInstructions UsingproperC++syntax,convertthefollowingifthenelsetoaconditionalexpression. Example17.5:ifthenelse ifx==y { z=14; } else { z++; } 17.3.6.2Problem17bInstructions UsingproperC++syntax,convertthefollowingconditionalexpressiontoanifthenelse. Example17.6:conditional answer=y < z?47:92;

PAGE 220

212 CHAPTER17.17.CONDITIONALOPERATORANDRECURSION SolutionstoExercisesinChapter17 SolutiontoExercise17.1p.210 Answers: 1.false 2.true 3.true 4.false 5.false

PAGE 221

Chapter18 18.IntroductiontoArrays 18.1ArrayDataType 1 18.1.1Overview An array isasequencedcollectionofelementsofthesamedatatypewithasingleidentiername.Assuch, thearraydatatypebelongstothe"Complex"categoryorfamilyofdatatypes.Arrayscanhavemultiple axesmorethanoneaxis.Eachaxisisa dimension .Thusasingledimensionarrayisalsoknownasa list Atwodimensionarrayiscommonlyknownasa table aspreadsheetlikeExcelisatwodimensionarray. Inreallifethereareoccasionstohavedataorganizedintomultipledimensionedarrays.Consideratheater ticketwithsection,rowandseatthreedimensions.Thismodulewillonlycoverthesingledimensionarray. Mostsingledimensionarraysarevisualizedverticallyandareoftencalledalist. Mostprogrammersarefamiliarwithaspecialtypeofarraycalleda string .Stringsarebasicallya singledimensionarrayofcharacters.Unlikeothersingledimensionarrays,weusuallyenvisionastring asahorizontalstreamofcharactersandnotverticallyasalist.WithinC++thestringdatatypeisa length-controlledarrayandisapre-deneddataclass. Werefertotheindividualvaluesasmembersorelementsofthearray.Programminglanguagesimplementthedetailsofarraysdierently.Becausethereisonlyoneidentiernameassignedtothearray,wehave operatorsthatallowustoreferenceoraccesstheindividualmembersofanarray.Theoperatorcommonly associatedwithreferencingarraymembersisthe index operator.Itisimportanttolearnhowtodenean arrayandinitializeitsmembers.Additionally,the sizeof operatorisoftenusedtocalculatethenumberof membersinanarray. 18.1.2DeninganArrayinC++ Example: intages[5]={49,48,26,19,16}; Thisisthe deningofstoragespace .Thesquarebracketsleft[andright]areusedheretocreate thearraywithveintegermembersandtheidentiernameofages.Theassignmentwithbracesthatisa blockestablishestheinitialvaluesassignedtothemembersofthearray.Notetheuseofthesequenceor commaoperator.Wecouldhavedoneitthisway: intages[]={49,48,26,19,16}; Byleavingouttheveandhavinginitialvaluesassigned,thecompilerwillknowtocreatethearraywith vestoragespacesbecausetherearevevalueslisted.Thismethodispreferredbecausewecansimplyadd memberstoorremovemembersfromthearraybychangingtheitemsinsideofthebraces.Wecouldhave alsodonethis: 1 Thiscontentisavailableonlineat. 213

PAGE 222

214 CHAPTER18.18.INTRODUCTIONTOARRAYS intages[5]; Thiswouldhavedeclaredthestoragespaceofveintegerswiththeidentiernameofagesbuttheir initialvalueswouldhavebeenunknownvaluesactuallytherewouldbevaluestherebutwedon'tknow whattheywouldbeandthusthinkofthevaluesasgarbage.Wecouldassignvalueslaterinourprogram bydoingthis: ages[0]=49; ages[1]=48; ages[2]=26; ages[3]=19; ages[4]=16; note: Themembersofthearraygofrom0to4; NOT 1to5.Thisisexplainedinmoredetailin anotherConnexionsmodulethatcoversaccessingarraymembersandislistedinthesupplemental linksprovided.See:ArrayIndexOperator. 18.1.3Denitions Denition18.1:dimension Anaxisofanarray. Denition18.2:list Asingledimensionarray. Denition18.3:table Atwodimensionarray. 18.2ArrayIndexOperator 2 18.2.1ArrayIndexOperatorinC++ Example: intages[5]={49,48,26,19,16}; intmy_age; my_age=ages[2] Thissecondusageofthesquarebracketsisasthe arraynotationofdereference ormorecommonly calledthe indexoperator .Asanoperatoriteitherprovidesthevalueheldbythememberofthearray RvalueorchangesthevalueofmemberLvalue.Intheaboveexamplethememberthatistwoosets fromthefrontofthearraythevalue26isassignedtovariablenamedmy_age.Thedereferenceoperator of[2]meanstogothe2 nd oset fromthefrontoftheagesarrayandgetthevaluestoredthere.Inthiscase thevaluewouldbe26.Thearraymembersorelementsarereferencedstartingatzero.Themorecommon wayforpeopletoreferencealistisbystartingwithone.Manyprogramminglanguagesreferencearray membersstartingatone,howeverforsomelanguagesandC++isoneofthemyouwillneedto change yourthinking .Consider: 2 Thiscontentisavailableonlineat.

PAGE 223

215 Position C++ MissAmerica OtherContests zeroosetsfromthefront ages[0] Winner 1 st Place oneosetsfromthefront ages[1] 1 st RunnerUp 2 nd Place twoosetsfromthefront ages[2] 2 nd RunnerUp 3 rd Place threeosetsfromthefront ages[3] 3 rd RunnerUp 4 th Place fourosetsfromthefront ages[4] 4 th RunnerUp 5 th Place Table18.1 Sayingthatmycousinisthe2 nd RunnerUpintheMissAmericacontestsoundssomuchbetterthan sayingthatshewasin3 rd Place.Wewouldbetalkingaboutthesamepositioninthearrayoftheve nalists. ages[3]=20; Thisisanexampleofchanginganarray'svaluebyassigning20tothe4 th memberofthearrayand replacingthevalue19with20.ThisisanLvaluecontextbecausethearrayisontheleftsideofthe assignmentoperator. TheC++operatornameiscalledthearrayindexorsimplytheindexoperatoranditusesthesquare bracketsastheoperatorsymbols. 18.2.2Denitions Denition18.4:arraymember Anelementorvalueinanarray. Denition18.5:index Anoperatorthatallowsustoreferenceamemberofanarray. Denition18.6:oset Themethodofreferencingarraymembersbystartingatzero. 18.3DisplayingArrayMembers 3 18.3.1AccessingArrayMembersinC++ Example18.1:accessingthemembersofanarray intages[]={49,48,26,19,16}; intcounter; forcounter=0,counter < 5,counter++ { cout ages[counter] endl; } Thissecondusageofthesquarebracketsisasthe arraynotationofdereference ormorecommonlycalled the indexoperator .Asanoperatoritprovidesthevalueheldbythememberofthearray.Forexample, 3 Thiscontentisavailableonlineat.

PAGE 224

216 CHAPTER18.18.INTRODUCTIONTOARRAYS duringoneoftheiterationsoftheforlooptheindexwhichisanintegerdatatypewillhavethevalueof 3.Theexpressionages[counter]wouldinessencebe:ages[3].Thedereferenceoperatorof[3]meanstogo the3 rd osetfromthefrontoftheagesarrayandgetthevaluestoredthere.Inthiscasethevaluewould be19.Thearraymembersorelementsarereferencedstartingatzero.Themorecommonwayforpeople toreferencealistisbystartingwithone.Manyprogramminglanguagesreferencearraymembersstarting atone,howeverforsomelanguagesandC++isoneofthemyouwillneedto changeyourthinking Consider: Position C++ MissAmerica OtherContests zeroosetsfromthefront ages[0] Winner 1 st Place oneosetsfromthefront ages[1] 1 st RunnerUp 2 nd Place twoosetsfromthefront ages[2] 2 nd RunnerUp 3 rd Place threeosetsfromthefront ages[3] 3 rd RunnerUp 4 th Place fourosetsfromthefront ages[4] 4 th RunnerUp 5 th Place Table18.2 Sayingthatmycousinisthe2 nd RunnerUpintheMissAmericacontestsoundssomuchbetterthan sayingthatshewasin3 rd Place.Wewouldbetalkingaboutthesamepositioninthearrayoftheve nalists. Ratherthanusingtheforlooptodisplaythemembersofthearray,wecouldhavewrittenvelinesof codeasfollows: cout ages[0] endl; cout ages[1] endl; cout ages[2] endl; cout ages[3] endl; cout ages[4] endl; 18.3.2UsingtheSizeofOperatorwithArraysinC++ Example18.2:usingthesizeofoperator intages[]={49,48,26,19,16}; intcounter; forcounter=0,counter < sizeofages/sizeofages[0],counter++ { cout ages[counter] endl; } Withinthecontroloftheforloopforthedisplayingofthegrades,notethatwecalculatedthenumberof themembersinthearraybyusingthe sizeof operator.Theexpressionis: sizeofages/sizeofages[0] Whenyouaskforthesizeofanarrayidentiernametheanswerishowmanytotalbyteslongisthearray orinotherwordshowmanybytesofstoragedoesthisarrayneedtostoreitsvalues.Thiswilldepend

PAGE 225

217 onthedatatypeofthearrayandthenumberofelements.Whenyouaskforthesizeofoneofitsmembers, ittellsyouhowmanybytesonememberneeds.Bydividingthetotalnumberofbytesbythesizeofone member,wegettheanswerwewant:thenumberofmembersinthearray.Thismethodallowsfor exible coding .Bywritingtheforloopinthisfashion,wecanchangethedeclarationofthearraybyaddingor subtractingmembersandwedon'tneedtochangeourforloopcode. 18.3.3DemonstrationPrograminC++ 18.3.3.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 18.3.3.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Arrays.cpp 4 18.3.4Denitions Denition18.7:exiblecoding Usingthesizeofoperatortocalculatethenumberofmembersinanarray. 18.4Practice18:IntroductiontoArrays 5 18.4.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.WithinC++sourcecodebeabletodeneasingledimensionarray. 3.WithinC++sourcecodebeabletoaccessarraymembersusingtheindexoperator. 4.WithinC++sourcecodebeabletocalculatethenumberofmembersinanarrayusingthesizeof operator. 18.4.2MemoryBuildingActivities Linkto:MBA18 6 4 Seetheleat 5 Thiscontentisavailableonlineat. 6 Seetheleat

PAGE 226

218 CHAPTER18.18.INTRODUCTIONTOARRAYS 18.4.3Exercises Exercise18.1 Solutiononp.219. Answerthefollowingstatementsaseithertrueorfalse: 1.ThearraydatatypeisoneofthestandarddatatypesinC++. 2.Arrayscanhavemorethanonedimension. 3.Forloopsareoftenusedtodisplaythemembersofanarray. 4.Whendeninganarray,itispreferabletospecifyhowmanymembersareinthearray. 5.Arraysarerarelyusedtorepresentdata. 18.4.4MiscellaneousItems Noneatthistime. 18.4.5LabAssignment 18.4.5.1CreatingaFolderorSub-FolderforChapter18Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_18withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 18.4.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_18_Narrative_Description.txt 7 18.4.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefollowingthedirectionsintheLab_18_Narrative_Description.txtle.Name it:Lab_18.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 18.4.6Problems 18.4.6.1Problem18aInstructions Brieyexplainwhatanarrayisandlistthetwocommonoperatorsusedwitharrays. 7 Seetheleat

PAGE 227

219 SolutionstoExercisesinChapter18 SolutiontoExercise18.1p.218 Answers: 1.false 2.true 3.true 4.false 5.false

PAGE 228

220 CHAPTER18.18.INTRODUCTIONTOARRAYS

PAGE 229

Chapter19 19.FileI/OandArrayFunctions 19.1FileInputandOutput 1 19.1.1OverviewofFileI/OinC++ Weneedtounderstandhowtoopen,read,writeandclosetextles.ThefollowingFileInput/Outputterms areexplained: TextFile AleconsistingofcharactersfromtheASCIIcharactercodeset.Textlesalsoknowan ASCIItextlescontaincharacterdata.Whenwecreateatextleweusuallythinkofitconsistingofa seriesoflines.Oneachlineareseveralcharactersincludingspaces,punctuation,etc.andwegenerallyend thelinewithareturnthisacharacterwithintheASCIIcharactercodeset.Thereturnisalsoknownas thenewlinecharacter.Youaremostlikelyalreadyfamiliarwiththeescapecodeof n nwhichisusedwithin C++toindicateareturncharacterwhenusedwithinaliteralstringwiththecout. AtypicaltextleconsistingoflinescanbecreatedbytexteditorsNotepadorwordprocessingprograms MicrosoftWord.Whenusingawordprocessoryoumustusuallyspecifytheoutputleastext.txtwhen savingit.Most sourcecode lesareASCIItextleswithauniqueleextension;suchasC++using .cpp,Pascalusing.pas,Cobolusing.cob,etc.Thus,mostcompiler/IntegratedDevelopmentEnvironment softwarepackagessuchasthe BloodshedDev-C++5compiler/IDE canbeusedtocreateASCIItext les. Filename Thenameanditsextension.Mostoperatingsystemshaverestrictionsonwhichcharacters canbeusedinlenames.ExampleforMS-DOSandWindows:Lab_05.txt Becausesomeoperatingsystemsdonotallowspaces,wesuggestthatyouusethe underscore where neededforspacinginalename. Filespec Thelocationofalealongwithitslename.Itisshortforlespecication.Mostoperating systemshaveasetofrulesonhowtospecifythedriveanddirectoryorpaththroughseveraldirectory levelsalongwiththelename.ExampleforMS-DOSandWindows:C: n myles n cosc_1436 n Lab_05.txt Becausesomeoperatingsystemsdonotallowspaces,wesuggestthatyouusethe underscore where neededwhencreatingfoldersorsub-directories. Open Yourprogramrequestingtheoperatingsystemtoletithaveaccesstoanexistingleortoopen anewle.WithinC++thisisaccomplishedbyincludingtheheaderle: < fstream > FileInput/Outputis handledinC++byusingapre-denedclassofdataobjects,similartothewaystringdatatypeishandled. Thisclassofobjectshasbothdatatypenamesandfunctionsbuilttospecicallyaccomplishopeningand closingale. Withinyourprogramyoucreatealocalstoragevariablewiththedatatypeoffstreamlikethis: fstreaminData; 1 Thiscontentisavailableonlineat. 221

PAGE 230

222 CHAPTER19.19.FILEI/OANDARRAYFUNCTIONS Thisvariablewillbeusedtostorethedevicetokenthattheoperatingsystemassignstothelebeing opened.Thus,openingaleusesaclassmemberfunctioncalllikethis: inData.open"C: nn myfiles nn cosc_1436 nn Lab_05.txt",ios::in; Thetwoparameterspassedtothefunctionarethelespecandthemethodthatyouwanttousethele inthisexampleasinput.Thefunctionprovidesareturningvalueofa devicetoken fromtheoperating systemanditisstoredinthevariablenamedinData. Itisconsideredgoodprogrammingpracticetodetermineifthelewasopenedproperly.Thedevice tokenshouldbeanonzerovalue.Ittheoperatingsystemgivesyouthevalueofzeroitwasnotabletoopen thele.Thereasonitusuallycan'topenaleisbecausethelespeciswrongmisspelledornottypedcase consistentinsomeoperatingsystemsortheleisnotstoredinthelocationspecied.Weoftentestthe devicetokenbyusinganifthencontrolstructurewiththeactionconsistingofstoppingtheprogramifitis truethatyougotthezero.Therstlineoftheifthencontrolstructurelookslikethis: if!inData Don'tbemisledbythenotoperator.Thisreads"ifitistruethatthetokenstoredininDataiszero".If inDataiszero,notingzerois1ortrue. Read Movingdatafromadevicethathasbeenopenedintoamemorylocationdenedinyourprogram. Whenreadingtextlesthathaveintegeroroating-pointconstants,theoperatingsystemsconvertsthetext symbolstoabinarynumber.Theoperatorusedistheextractionorreadoperator.Anexampleofreading is: inData next_number Thisexpressionissimilartoreadingfromthestandardinputdeviceakathekeyboard: cin next_number The"cin"isapredeneddevicetokenassociatedwiththeStandardInputandOutputdevices.Forour lereadingexampleyoumightsay,"GotothedeviceidentiedbythetokenstoredintheinDatavariable andreadinthenextvaluestoringitinthenext_numbervariablewithinmyprogram". Write Movingdatafromamemorylocationdenedinyourprogramtoadevicethathasbeenopened. Whenwritingintegeroroating-pointdatatypes,theoperatingsystemconvertsthebinarynumberintothe propertextsymbols.Theoperatorusedistheinsertionorwriteoperator.Anexampleofwritingis: outData "Totalis:" total endl; Thisexpressionissimilartowritingtothestandardoutputdeviceakathemonitor: cout "Totalis:" total endl; The"cout"isapredeneddevicetokenassociatedwiththeStandardInputandOutputdevices.Forour lewritingexampleyoumightsay,"GotothedeviceidentiedbythetokenstoredintheoutDatavariable andwritetheitemslistedthestringconstantthenthevaluestoredinmyprogramvariablenamedtotal thentheendlornewlineorthereturncharacter". Close Yourprogramrequestingtheoperatingsystemtoreleasealethatwaspreviouslyopened. Therearetworeasonstocloseale.First,itreleasestheleandfreesuptheassociatedoperationsystem resources.Second,ifclosingalethatwasopenedforoutput;itwillcleartheouttheoperatingsystem's buerandinsurethatallofthedataisphysicallystoredintheoutputle.Someexamplesofclosingles: inData.close; outData.close; Youneedtostudythismoduleinconjunctionwiththedemoleprovided. 19.1.2DemonstrationPrograminC++ 19.1.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs

PAGE 231

223 Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 19.1.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_File_IO.cpp 2 DownloadfromConnexions:Demo_File_IO_Input.txt 3 Afteryouruntheprogramuseatexteditortoexaminethe Demo_File_IO_Output.txt lecreated bytheprogram.Youshouldseetheoutputas: Totalis:33.3 19.1.3Denitions Denition19.1:textle AleconsistingofcharactersfromtheASCIIcharactercodeset. Denition19.2:lename Thenameanditsextension. Denition19.3:lespec Thelocationofalealongwithitslename. Denition19.4:open Yourprogramrequestingtheoperatingsystemtoletithaveaccesstoanexistingleortoopena newle. Denition19.5:devicetoken Akeyvalueprovidedbytheoperatingsystemtoassociateadevicetoyourprogram. Denition19.6:read Movingdatafromadevicethathasbeenopenedintoamemorylocationdenedinyourprogram. Denition19.7:write Movingdatafromamemorylocationdenedinyourprogramtoadevicethathasbeenopened. Denition19.8:close Yourprogramrequestingtheoperatingsystemtoreleasealethatwaspreviouslyopened. 19.2ArraysandFunctions 4 19.2.1OverviewofArrayFunctions Arraysareanimportantcomplexdatatypeusedinalmostallprogramming.Wecontinuetoconcentrateon simpleonedimensionarraysalsocalledalist.Mostprogrammersdevelopaseriesof userdenedspecic task functionsthatcanbeusedwithanarrayfornormalprocessing.Thesefunctionsareusuallypassedthe arrayalongwiththenumberofelementswithinthearray.Someoffunctionsalsopassanotherpieceofdata neededforthatparticularfunctionstask. Thismodulecoversthedisplayingthearraymembersonthemonitorviacallingan arrayfunction dedicatedtothattask.Youneedtostudythismoduleinconjunctionwiththedemoleprovided. 2 Seetheleat 3 Seetheleat 4 Thiscontentisavailableonlineat.

PAGE 232

224 CHAPTER19.19.FILEI/OANDARRAYFUNCTIONS 19.2.2DemonstrationPrograminC++ 19.2.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 19.2.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials. DownloadfromConnexions:Demo_Array_Display_Function.cpp 5 19.2.3Denitions Denition19.9:arrayfunction Auserdenedspecictaskfunctiondesignedtoprocessanarray. 19.3LoadinganArrayfromaFile 6 19.3.1ConceptualOverview Loadinganarrayfromalepresentsaninterestingdilemma.Theproblemresolvesaroundhowmany elementsyoushouldplanforinthearray.Let'ssay100,butwhatifthelehasfewerormorethan100 values.Howcantheprogramhandleitcorrectly? Thesolutioninvolvessomesimplesteps: 1.Wecanreadtheleoncetogettheelementcount.Thus,wewillknowexactlyhowmanymembers elementswewillneed. 2.Wecanthencreateanarrayusing dynamicmemoryallocation bydeningthearraywithina functionsothatithas localscope .Localscopevariablesarecreatedduringtheexecutionofthe programandusethestackasthestoragelocationinsteadofthedataarea.Ifyoudenethearray outsideofafunction globalscope alsoknownas staticmemoryallocation itstoresitinthedata areaandmustknowhowmuchstoragespacetoallocatetothearraywhenyou writethesource code .Sincewedon'tknowhowmanyelementswillbeontheinputlewhenwewritethesourcecode deninganarraywithglobalscopewillnotwork.But,wecandetermineexactlyhowmanymembers weneedforthearraybyhavingourprogramcountthemstep1sothatwecanthendenethearray withlocalscopetotheprecisesizeneeded. 3.Wecanthenloadthearraybyreadingtheleasecondtimeandstoringthevaluesreadintothearray justcreated. Thismethodisdemonstratedinthedemoleprovided,thusyouneedtostudythismaterialinconjunction withthedemoprogram. 5 Seetheleat 6 Thiscontentisavailableonlineat.

PAGE 233

225 19.3.2DemonstrationPrograminC++ 19.3.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 19.3.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_Loading_Array_from_File.cpp 7 DownloadfromConnexions:Demo_Farm_Acres_Input.txt 8 19.3.3Denitions Denition19.10:dynamicmemory Akastackcreatedmemoryassociatedwithlocalscope. Denition19.11:staticmemory Akadataareamemoryassociatedwithglobalscope. 19.4MathStatisticswithArrays 9 19.4.1Overview Arraysareanimportantcomplexdatatypeusedinalmostallprogramming.Wecontinuetoconcentrateon simpleonedimensionarraysalsocalledalist.Mostprogrammersdevelopaseriesof userdenedspecic task functionsthatcanbeusedwithanarrayfornormalprocessing.Thesefunctionsareusuallypassedthe arrayalongwiththenumberofelementswithinthearray.Someoffunctionsalsopassanotherpieceofdata neededforthatparticularfunctionstask. Thismodulecoversthetotalingofthemembersofanintegerarraymember.TheLatinnamefortotaling issummasometimesshortenedtotheword sum .The arrayfunction isoftencalled"sum"anditdoes someparameterpassing.Itpassesintothefunctionthecommontwoitemsofthearray:itsnamealongwith thenumberofelements;butitalsoreturnsavaluerepresentingsumortotalofthevalueswithinthearray. Youneedtostudythismoduleinconjunctionwiththedemoleprovided. Othermathematicalfunctionsoftenassociatedwithstatisticssuchas:average,count,minimum,maximum,standarddeviation,etc.areoftendevelopedforprocessingarrays. 7 Seetheleat 8 Seetheleat 9 Thiscontentisavailableonlineat.

PAGE 234

226 CHAPTER19.19.FILEI/OANDARRAYFUNCTIONS 19.4.2DemonstrationPrograminC++ 19.4.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 19.4.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_Sum_Array_Function.cpp 10 DownloadfromConnexions:Demo_Farm_Acres_Input.txt 11 19.4.3Denitions Denition19.12:sum Latinforsummaoratotal. 19.5Practice19:FileI/OandArrayFunctions 12 19.5.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.WithinC++sourcecodebeabletounderstandbasicleinputandleoutput. 3.Understandwhywetesttoseeifalewasopenedproperly. 4.Understandwhyweclosealewhenwearedonewithit. 5.WithinC++sourcecodebeabletounderstandfunctionsforarrays,specicallycountingthenumber ofelementsinalesoyoucandeneanarray,loadthatarraywiththoseelements,displaythearray andsumthearray. 6.WithinC++sourcecodebeabletocreatefunctionsforarrays,specicallyafunctionforaveraging. 19.5.2MemoryBuildingActivities Linkto:MBA19 13 10 Seetheleat 11 Seetheleat 12 Thiscontentisavailableonlineat. 13 Seetheleat

PAGE 235

227 19.5.3Exercises Exercise19.1 Solutiononp.228. Answerthefollowingstatementsaseithertrueorfalse: 1.Textlesarehardtocreate. 2.Alespecreferstoaverysmalllikeaspecdustle. 3.Adevicetokenisaspecialnonzerovaluetheoperatingsystemgivesyourprogramandis associatedwiththelethatyourequestedtobeopened. 4.Programmersshouldnotworryaboutclosingale. 5.Whereyoudeneanitem,thatisglobalorlocalscope,israrelyimportant. 19.5.4MiscellaneousItems Noneatthistime. 19.5.5LabAssignment 19.5.5.1CreatingaFolderorSub-FolderforChapter19Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_19withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 19.5.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_19_Narrative_Description.txt 14 19.5.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefollowingthedirectionsintheLab_19_Narrative_Description.txtle.Name it:Lab_19.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 19.5.6Problems 19.5.6.1Problem19aInstructions Forwhatpurposedoweusethesizeofoperatorwithanarray. 19.5.6.2Problem19bInstructions Whywouldweopenaleandcountitselementsandthenclosethele. 14 Seetheleat

PAGE 236

228 CHAPTER19.19.FILEI/OANDARRAYFUNCTIONS SolutionstoExercisesinChapter19 SolutiontoExercise19.1p.227 Answers: 1.false 2.false 3.true 4.false 5.false

PAGE 237

Chapter20 20.MoreArrayFunctions 20.1FindingaSpecicMemberofanArray 1 20.1.1Overview Findingaspecicmemberofanarraymeanssearchingthearrayuntilthememberisfound.It'spossible thatthememberdoesnotexistandtheprogrammermusthandlethatpossibilitywithinthelogicofhis algorithm.Twospecicsearchescanbemadeforthemaximumlargestvaluesinthearrayortheminimum smallestvalueinthearray.Maximumandminimumarealsoknowasmaxandmin. Therearetwobasicwaysofsearchingforaspecicvalue: 1.Linearsearch 2.Binarysearch "Thelinearsearchisaverysimplealgorithm.Sometimescalledasequentialsearch,itusesaloopto sequentiallystepthroughanarray,startingwiththerstelement.Itcompareseachelementwiththevalue beingsearchfor,andstopswheneitherthevalueisfoundortheendofthearrayisencountered.Ifthevalue beingsearchedforisnotinthearray,thealgorithmwillsearchtotheendofthearray." 2 Binarysearchisnotcoverinthismodule.Linearsearchandsearchingforthemaximumisdemonstrated inthedemoleprovided,thusyouneedtostudythismaterialinconjunctionwiththedemoprogram. 20.1.2DemonstrationPrograminC++ 20.1.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 1 Thiscontentisavailableonlineat. 2 TonyGaddis,JudyWaltersandGodfreyMuganda, Starting Out with C++ Early Objects Sixth EditionUnitedStatesof America:PearsonAddisonWesley,2008559. 229

PAGE 238

230 CHAPTER20.20.MOREARRAYFUNCTIONS 20.1.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_FindingArrayMember.cpp 3 DownloadfromConnexions:Demo_Farm_Acres_Input.txt 4 20.1.3Denitions Denition20.1:linearsearch Usingalooptosequentiallystepthroughanarray. Denition20.2:maximum Akamaxorthelargestmemberofanarray. Denition20.3:minimum Akaminorthesmallestmemberofanarray. 20.2SortinganArray 5 20.2.1Overview Sortingistheprocessthroughwhichdataarearrangedaccordingtotheirvalues.Thereareseveralsorting algorithmsormethodsthatcanbeusedtosortdata.Someinclude: 1.Bubble 2.Selection 3.Insertion Wewillnotbecoveringtheselectionorinsertionsortmethodsinthismodule. "Thebubblesortisaneasywaytoarrangedatainascendingordescendingorder.Ifanarrayissorted inascendingorder,itmeansthevaluesinthearrayarestoredfromlowesttohighest.Ifvaluesaresorted indescendingorder,theyarestoredfromhighesttolowest.Bubblesortworksbycomparingeachelement withitsneighborandswappingthemittheyarenotinthedesiredorder." 6 Thereareseveraldierentmethodsofbubblesortingandsomemethodsaremoreecientthanothers. Mostuseapairofnestedloopsoriterationcontrolstructures.Onemethodsetsaagthatindicatesthat thearrayissorted,thendoesapassandifanyelementsareexchangedswitched;itsetstheagtoindicate thatthearrayisnotsorted.Itisexecuteduntilitmakesapassandnothingisexchanged. 3 Seetheleat 4 Seetheleat 5 Thiscontentisavailableonlineat. 6 TonyGaddis,JudyWaltersandGodfreyMuganda, Starting Out with C++ Early Objects Sixth EditionUnitedStatesof America:PearsonAddisonWesley,2008569.

PAGE 239

231 Figure20.1 Thebubblesortgetsitsnamefromthelighterbubblesthatmoveor"bubbleup"tothetopofaglassof sodapop.Wemovethesmallerelementsofthearraytothetopasthelargerelementsmovetothebottom ofthearray.Thiscanbeviewedfromadierentperspective.UsinganItaliansaladdressingwithoil,water andherbs;onceshakenyoucaneither: 1.envisionthelighteroilrisingtothetop; OR 2.envisiontheheaverwaterandherbssinkingtothebottom Eitherwayiscorrectandthisversionofthecodesimplydemonstratesthesinkingtothebottomtheheaver orlargerelementsofthearray. Bubblesortingisdemonstratedinthedemoleprovided,thusyouneedtostudythismaterialinconjunctionwiththedemoprogram. 20.2.2DemonstrationPrograminC++ 20.2.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed:

PAGE 240

232 CHAPTER20.20.MOREARRAYFUNCTIONS Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 20.2.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_Sort_Array_Function.cpp 7 DownloadfromConnexions:Demo_Farm_Acres_Input.txt 8 20.2.3Denitions Denition20.4:sorting Arrangingdataaccordingtotheirvalues. Denition20.5:bubblesort Amethodofswappingarraymembersuntiltheyareinthedesiredsequence. 20.3Practice20:MoreArrayFunctions 9 20.3.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.WithinC++sourcecodebeabletounderstandfunctionsforarrays,specicallysearchingaarray's valuestoseeifagivenvalueexists,ndingthemaximumvalueinanarrayandsortinganarray. 3.WithinC++sourcecodebeabletocreatefunctionsforarrays,specicallyafunctionforndingthe smallestvalueinanarray. 4.WithinC++sourcecodebeabletomodifyingexistingcodetoprocessdierenttypesofarrays. 20.3.2MemoryBuildingActivities Linkto:MBA20 10 20.3.3Exercises Exercise20.1 Solutiononp.234. Answerthefollowingstatementsaseithertrueorfalse: 1.Linearsearchesrequirecomplexalgorithms. 2.Functionsareoftencreatedforsearchingforthemaxandminvaluesinanarray. 3.Thebubblesortisaneasywaytoarrangedataanarray. 4.Thereisonlyonemethodofbubblesorting. 7 Seetheleat 8 Seetheleat 9 Thiscontentisavailableonlineat. 10 Seetheleat

PAGE 241

233 5.Sortinganarrayisfrequentlydone. 20.3.4MiscellaneousItems Noneatthistime. 20.3.5LabAssignment 20.3.5.1CreatingaFolderorSub-FolderforChapter20Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_20withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 20.3.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_20_Narrative_Description.txt 11 20.3.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefollowingthedirectionsintheLab_20_Narrative_Description.txtle.Name it:Lab_20.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 20.3.6Problems 20.3.6.1Problem20aInstructions Giveashortexplanationofbubblesorting. 11 Seetheleat

PAGE 242

234 CHAPTER20.20.MOREARRAYFUNCTIONS SolutionstoExercisesinChapter20 SolutiontoExercise20.1p.232 Answers: 1.false 2.true 3.true 4.false 5.true

PAGE 243

Chapter21 21.MoreonTypedef 21.1VersatileCodewithTypedef 1 21.1.1Overview Everyoneseeksofwaystobemoreecientinwhattheydo.Aframerusesatractorinsteadofahorse.A constructionworkerusesanairpowerednailguninsteadofahammer.Programmersarenodierentthan others,inthattheyareconstantlyimprovingtheirabilitytoproducecorrectlyworkingprograms.Some aspectofthisistheuseofmodular/structuredprogramming,properdocumentationandfollowingindustry rulesforaspecicprogramminglanguage.Oneexampleofecientcodingislettingthecomputercountthe numberofelementsinanarray.Ifwedeneanarray: intages[]={33,32,10,3}; Wecanusethefollowingexpressiontocalculatethenumberofmembersinthearray: sizeofages/sizeofages[0] Thistypeof exiblecoding allowsustochangethemembersofthearraybyaddingorsubtractinga values,likethis: intages[]={57,33,32,3,1}; Thus,wedon'thavetomodifyourcodethatusestheexpressionthatcalculatesthenumberofmember inthearray. Oneuseofthe typedef istoallowustowritecodethatcanbequicklychangedtohandledierentdata types.Thereareseveralintegerandoating-pointdatatypesthatallstorenumbervalueswithdierent domains.Ifwewriteourcodeusingsometypedefstatement,thenourcodebecomes versatile .Bychanging onlyourtypedefcommands,ourcodecanbeusedtoprocessdataofadierentdatatype.Thisisdemonstratedwithinthedemoleprovided,thusyouneedtostudythismaterialinconjunctionwiththedemo program. 21.1.2DemonstrationPrograminC++ 21.1.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 1 Thiscontentisavailableonlineat. 235

PAGE 244

236 CHAPTER21.21.MOREONTYPEDEF 21.1.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_Versatile_Array_Functions.cpp 2 DownloadfromConnexions:Demo_Farm_Acres_Input.txt 3 DownloadfromConnexions:Demo_Deposit_Checks_Input.txt 4 21.1.3Denitions Denition21.1:versatile Easilymodifyingcodetohandleanotherdatatype. Denition21.2:exiblecoding Usingthesizeofoperatortocalculatethenumberofmembersinanarray. Denition21.3:typedef Allowstheprogrammertocreateanalias,orsynonym,foranexistingdatatype. 21.2Practice21:MoreonTypedef 5 21.2.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.UnderstandhowtypedefisusedwithinC++sourcecodebeablemakethecodeversatilethatiseasy tochangefordierentdatatypes. 21.2.2MemoryBuildingActivities Linkto:MBA21 6 21.2.3Exercises Exercise21.1 Solutiononp.238. Answerthefollowingstatementsaseithertrueorfalse: 1.Mostprogrammersrarelyworryabouteciency. 2.Modular/structuredprogramminghelpsimproveeciency. 3.Flexiblecodinghelpsimproveeciency. 4.Whocaresaboutindentationandalignmentwithinsourcecode.It'sawasteoftime. 5.Versatilecodeisaconceptthatiseasytounderstand. 2 Seetheleat 3 Seetheleat 4 Seetheleat 5 Thiscontentisavailableonlineat. 6 Seetheleat

PAGE 245

237 21.2.4MiscellaneousItems Noneatthistime. 21.2.5LabAssignment 21.2.5.1CreatingaFolderorSub-FolderforChapter18Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_18withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 21.2.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_21_Narrative_Description.txt 7 DownloadfromConnexions:Lab_21_Input.txt 8 21.2.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefollowingthedirectionsintheLab_21_Narrative_Description.txtle.Name it:Lab_21.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 21.2.6Problems 21.2.6.1Problem21aInstructions Explainthedierencebetweenexiblecodingandversatilecoding. 7 Seetheleat 8 Seetheleat

PAGE 246

238 CHAPTER21.21.MOREONTYPEDEF SolutionstoExercisesinChapter21 SolutiontoExercise21.1p.236 Answers: 1.falseEciencyofcodeexecution,no;eciencyofcodeproductionandmaintenance,yes. 2.true 3.true 4.false 5.maybetrueandmaybefalseItdoesrequiresomeeorttocatchontohowitworks.

PAGE 247

Chapter22 22.Pointers 22.1AddressOperator 1 22.1.1AddressOperatorinC++ "Everyvariableisassignedamemorylocationwhoseaddresscanberetrievedusingtheaddressoperator&. Theaddressofamemorylocationiscalledapointer.Everyvariableinanexecutingprogramisallocated asectionofmemorylargeenoughtoholdavalueofthatvariable'stype." 2 Thus,whetherthevariablesare globalscope andusethedataareaforstorageor localscope andusethestackforstorage;youcanask thequestionatwhataddressinthememorydoesthisvariableexist.Givenanintegervariablenamedage: intage=47; Wecanusethe addressoperator [whichisthe ampersand or&]todeterminewhereitexistsorits addressinthememoryby: &age Thisexpressionisa pointer datatype.Theconceptofanaddressandapointerareoneinthesame. Apointerpointstothelocationinmemorybecausethevalueofapointeristheaddresswerethedataitem residesinthememory. Theaddressoperatoriscommonlyusedintwoways: 1.Todoparameterpassingbyreference 2.Toestablishthevalueofpointers Bothoftheseitemsarecoveredinthesupplementallinkstothismodule. Youcanprintoutthevalueoftheaddresswiththefollowingcode: cout &age; Thiswillbydefaultprintthevalueinhexadecimal.Somepeoplepreferanintegervalueandtoprintit asanintegeryouwillneedtocasttheaddressintoalongdatatype: cout long&age; Oneadditionaltidbit,anarray'snameisbydenitionapointertothearraysrstelement.Thus: intiqs[]={122,105,131,97}; establishes"iqs"asapointertothearray. 22.1.2Denitions Denition22.1:addressoperator Theampersandor&. 1 Thiscontentisavailableonlineat. 2 TonyGaddis,JudyWaltersandGodfreyMuganda, Starting Out with C++ Early Objects Sixth EditionUnitedStatesof America:PearsonAddisonWesley,2008597. 239

PAGE 248

240 CHAPTER22.22.POINTERS Denition22.2:pointer Avariablethatholdsanaddressasitsvalue. 22.2ParameterPassingbyReference 3 22.2.1Overview Whenwepassparameterstofunctionsweusuallypassbyvalue;thatisthecallingfunctionprovidesseveral valuestothecalledfunctionasneeded.Thecalledfunctiontakesthesevalueswhichhave localscope and storesthemonthestackusingthemasneededforwhateverprocessingthefunctionsaccomplishes.This isthepreferredmethodwhencallinguserdenedspecictaskfunctions.Thecalledfunctionpassesback asinglevalueasthereturnitemifneeded.Thishastheadvantageofa closedcommunicationsmodel witheverythingbeingneatlypassedinasvaluesandanyneededitemreturnedbackasaparameter. Bynecessitytherearetwoexceptionstothisclosedcommunicationsmodel: 1.Whenweneedmorethanoneitemofinformationreturnedbythefunction 2.Whenacopyofanargumentcannotreasonablyorcorrectlybemadeexample:lestreamobjects. Theseexceptionsarehandledbyparameterpassingbyreferenceinsteadofpassingavalue.Theitempassed iscalleda referencevariable anditrepresentsaconceptofanaliasforthevariable.Anychangemadeto thereferencevariableisactuallyperformedonthevariablethatitrepresents.Thesymboloftheampersand isusedtodesignatethereferencevariableanditisassociatedwiththeaddressoperator. Example22.1:parameterpassingbyreference //prototype voidprocess_valuesintqty_dimes,intqty_quarters,double&value_dimes,double&value_quarters; //variabledefinitions intdimes=45; intquarters=33; doublevalue_dimes; doublevalue_quarters; //somewhereinthefunctionmain process_valuesdimes,quarters,value_dimes,value_quarters; //definitionofthefunction voidprocess_valuesintqty_dimes,intqty_quarters,double&value_dimes,double&value_quarters; { value_dimes=dimes*0.10; value_quarters=quarters*0.25; } note: Theampersandmustappearinboththeprototypeandthefunctiondenitionbutitdoes notappearinthefunctioncall. Theaboveexampleshowsthebasicmechanicsofparameterpassingbyreference.Youshouldstudythe demonstrationprograminconjunctionwiththismodule. 3 Thiscontentisavailableonlineat.

PAGE 249

241 22.2.2DemonstrationPrograminC++ 22.2.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 22.2.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_Parameter_Passing.cpp 4 22.2.3Denitions Denition22.3:referencevariable Usedwithparameterpassingbyreference. 22.3PointerDataType 5 22.3.1PointerDataTypeinC++ A pointer variableisavariablethatholdstheaddressofamemorylocation."Everyvariableisassigned amemorylocationwhoseaddresscanberetrievedusingtheaddressoperator&.Theaddressofamemory locationiscalledapointer." 6 The pointerdatatype allowsustodesignateavariabletoholdanaddress orapointer.Theconceptofanaddressandapointerareoneinthesame.Apointerpointstothelocation inmemorybecausethevalueofapointeristheaddresswerethedataitemresidesinthememory.Given anintegervariablenamedage: intage=47; Wecancreateapointervariableandestablishitsvaluewhichwouldbethedoneusingthe address operator [whichisthe ampersand or&]by: int*int_pointer=&age; The asterisk isusedtodesignatethatthevariableint_pointerisanintegerpointer[int*].Thismeans thatwheneverweusethevariableint_pointerthatthecompilerwillknowthatitisapointerthatpoints toaninteger. Inordertousepointersyouwillneedtounderstandthe indirectionoperator whichiscovereda supplementallink. 22.3.2Denitions Denition22.4:pointer Avariablethatholdsanaddressasitsvalue. 4 Seetheleat 5 Thiscontentisavailableonlineat. 6 TonyGaddis,JudyWaltersandGodfreyMuganda, Starting Out with C++ Early Objects Sixth EditionUnitedStatesof America:PearsonAddisonWesley,2008597.

PAGE 250

242 CHAPTER22.22.POINTERS 22.4IndirectionOperator 7 22.4.1IndirectionOperatorinC++ Whenwepassparameterstofunctionsweusuallypassbyvalue;thatisthecallingfunctionprovidesseveral valuestothecalledfunctionasneeded.Thecalledfunctiontakesthesevalueswhichhave localscope and storesthemonthestackusingthemasneededforwhateverprocessingthefunctionsaccomplishes.This isthepreferredmethodwhencallinguserdenedspecictaskfunctions.Thecalledfunctionpassesback asinglevalueasthereturnitemifneeded.Thishastheadvantageofa closedcommunicationsmodel witheverythingbeingneatlypassedinasvaluesandanyneededitemreturnedbackasaparameter. Bynecessitytherearetwoexceptionstothisclosedcommunicationsmodel: 1.Whenweneedmorethanoneitemofinformationreturnedbythefunction 2.Whenacopyofanargumentcannotreasonablyorcorrectlybemadeexample:lestreamobjects. Theseexceptionscouldbehandledbyparameterpassingbyreferenceinsteadofpassingavalue.Although dierentsyntaxthanparameterpassingwhenusinga referencevariable ;usinga pointer variableand the indirectionoperator canaccomplishthesameeect.Theindirectionoperatoristhe asterisk orthe characterthatwealsouseformultiplication.Theconceptofindirectionisalsoknownas dereferencing meaningthatwearenotinterestedinthepointerbutwanttheitemtowhichtheaddressisreferringor referencing. Example22.2:parameterpassingwithpointers //prototype voidprocess_valuesintqty_dimes,intqty_quarters,double*ptr_value_dimes,double*ptr_value_quarters; //variabledefinitions intdimes=45; intquarters=33; doublevalue_dimes; doublevalue_quarters; double*ptr_value_dimes=&value_dimes; double*ptr_value_quarters=&value_quarters; //somewhereinthefunctionmain process_valuesdimes,quarters,ptr_value_dimes,ptr_value_quarters; //definitionofthefunction voidprocess_valuesintqty_dimes,intqty_quarters,double*ptr_value_dimes,double*ptr_quarters; { *ptr_value_dimes=dimes*0.10; *ptr_value_quarters=quarters*0.25; } note: Theasteriskandmustappearinboththeprototypeandthefunctiondenitionwhen deningthepointervariablesbutitdoesnotappearinthefunctioncallwhenthepointersare passedintothefunction. 7 Thiscontentisavailableonlineat.

PAGE 251

243 Theaboveexampleshowsthebasicmechanicsoftheindirectionoperator. Theuseofpointerswithindirectionisoftenpreferredforprocessingarrays.The arrayindexoperator isalsoknownasthe arraymethodofdereferencing .Thefollowingcoutsareequivalent: intages[]={47,45,18,11,9}; cout ages[3]; cout *ages+3; Thebothsay,"Thenameofanarrayisapointer;takethepointerandcalculateanewaddressthat pointstothe3 rd osetbyaddingthecorrectnumberofbytesontothepointerintegerdatatypeisnormally 4byteslong3osetstimes4bytesis12bytes;thendereferencethatpointersincethisisanRvalue contextfetchmethevaluethatyouarepointingatandsendittothestandardoutputdevice." Youshouldstudythedemonstrationprogramsinconjunctionwiththismodule. 22.4.2DemonstrationPrograminC++ 22.4.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 22.4.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_Pointer_Passing.cpp 8 DownloadfromConnexions:Demo_Array_Pointer_Processing.cpp 9 22.4.3Denitions Denition22.5:indirectionoperator Theasteriskusedfordereferencingapointer. Denition22.6:dereferencing Theconceptofusingtheitemtowhichapointeroraddressispointingat. 22.5Practice22:Pointers 10 22.5.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 8 Seetheleat 9 Seetheleat 10 Thiscontentisavailableonlineat.

PAGE 252

244 CHAPTER22.22.POINTERS 2.Acquireageneralunderstandingofthepointerdatatype,theaddressandindirectionoperators,the conceptofdereferencing. 3.Givenpseudocode,writetheC++codeforaprogramthatusesreferencevariables. 22.5.2MemoryBuildingActivities Linkto:MBA22 11 22.5.3Exercises Exercise22.1 Solutiononp.246. Answerthefollowingstatementsaseithertrueorfalse: 1.Theaddressoperatoristhe@symbol. 2.Passingbyreferenceshouldbeusedwhenthereisonlyoneitemtobemodied. 3.Variablesofpointerdatatypearedenedusinganasterisk. 4.Usingpointerswiththeindirectionoperatorcanbeusedinsteadofpassingvariablesby reference. 5.Therearetwokindsofdereferencingonewiththeindirectionoperatorandtheotherwith theindexoperator. 22.5.4MiscellaneousItems Noneatthistime. 22.5.5LabAssignment 22.5.5.1CreatingaFolderorSub-FolderforChapter22Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_22withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 22.5.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_22_Pseudocode.txt 12 22.5.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefromtheLab_22_Pseudocode.txtle.Nameit:Lab_22.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 11 Seetheleat 12 Seetheleat

PAGE 253

245 22.5.6Problems 22.5.6.1Problem22aInstructions Giveageneralexplanationofthepointerdatatypeandtheuseofaddressesanddereferencing.Includeboth theindirectionoperatorandtheindexoperatorinyourdiscussion.

PAGE 254

246 CHAPTER22.22.POINTERS SolutionstoExercisesinChapter22 SolutiontoExercise22.1p.244 Answers: 1.false 2.false 3.true 4.true 5.true

PAGE 255

Chapter23 23.MoreArrays&CompilerDirectives 23.1MultidimensionalArrays 1 23.1.1Overview An array isasequencedcollectionofelementsofthesamedatatypewithasingleidentiername.Assuch, thearraydatatypebelongstothe"Complex"categoryorfamilyofdatatypes.Arrayscanhavemultiple axesmorethanoneaxis.Eachaxisisa dimension .Thusasingledimensionarrayisalsoknownasa list Atwodimensionarrayiscommonlyknownasa table aspreadsheetlikeExcelisatwodimensionarray. Inreallifethereareoccasionstohavedataorganizedintomultipledimensionedarrays.Consideratheater ticketwithsection,rowandseatthreedimensions. Werefertotheindividualvaluesasmembersorelementsofthearray.Programminglanguagesimplementthedetailsofarraysdierently.Becausethereisonlyoneidentiernameassignedtothearray,we haveoperatorsthatallowustoreferenceoraccesstheindividualmembersofanarray. Theoperatorcommonlyassociatedwithreferencingan arraymember isthe index operator.Itis importanttolearnhowtodeneanarrayandinitializeitsmembers.Theindexoperatorisasetofsquare bracketswithanintegervaluebetweenthebracketsthatrepresentsthe oset fromthefrontofthearray. Multidimensionalarraysuseonesetofsquarebracketsperdimensionoraxisofthearray.Forexample atablewhichhastwodimensionswouldusetwosetsofsquarebracketstodenethearrayvariableandtwo setsofsquarebracketsfortheindexoperatorstoaccessthemembersofthearray. Becauseofthecomplexityformultidimensionalarrays,thedemonstrationprogramshowsatwodimension arrayandyoushouldstudyitinconjunctionwiththismodule. 23.1.2DemonstrationPrograminC++ 23.1.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 1 Thiscontentisavailableonlineat. 247

PAGE 256

248 CHAPTER23.23.MOREARRAYS&COMPILERDIRECTIVES 23.1.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_Multidimension_Arrays.cpp 2 23.1.3Denitions Denition23.1:dimension Anaxisofanarray. Denition23.2:list Asingledimensionarray. Denition23.3:table Atwodimensionarray. Denition23.4:arraymember Anelementorvalueinanarray. Denition23.5:index Anoperatorthatallowsustoreferenceamemberofanarray. Denition23.6:oset Themethodofreferencingarraymembersbystartingatzero. 23.2ConditionalCompilation 3 23.2.1Overview Asyouproceedinyourprogrammingcareer,theproblems/tasksthatneedsolvingbecomemorecomplex. Thedocumentationofthealgorithmdoneinpseudocodeorsomeothermethodwillstillneedtobeconvertedintoaprogrammingsolution.Inevitably,whenwritingthatsourcecodemistakeswillbeintroduced. Whenlearningthesyntaxofanewprogramminglanguage,programmerssometimesautomaticallythinkin theiroldlanguagesyntax,andmakemistakesthataresometimeshardtodetect. Theconceptofusingaagtoeitheractivateorhaveremaindormantcertainlinesofcodedesigned solelytohelpwiththedebuggingofaprogramhasexistedsincealmostthebeginningofmoderncomputer programming's.OneofthedebuggingtoolsavailablewithinC++is conditionalcompilation .For ourag,wewoulduseadenedconstantlike: #defineDEBUG1 Thenusinganothercompilerdirectivepair,the#ifand#endif,wecanhavethecompilerduringthe pre-processoreitherincludeornotincludeoneormorelinesofcode. #ifDEBUG cout n n*****DEBUGCode**Himom!"; #endif Ofcoursesaying"Himom!"isnotveryusefulfordebuggingyourcode.However,youcanusetestdata withconditionalcompilation.Aseriesofinputdatavaluesandaseriesofoutputpredictorscanbeplaced intheprogram.Thenyoucanturnonthedebugfeatureorturnthemowithyourdebuggingag. Youshouldstudythedemonstrationprograminconjunctionwiththismodule. 2 Seetheleat 3 Thiscontentisavailableonlineat.

PAGE 257

249 23.2.2DemonstrationPrograminC++ 23.2.2.1CreatingaFolderorSub-FolderforSourceCodeFiles Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Demo_Programs Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 23.2.2.2DownloadtheDemoProgram Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Followingthe methodsofyourcompiler/IDE,compileandruntheprograms.Studythesourcecodelesinconjunction withotherlearningmaterials.Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inorder todownloadthele. DownloadfromConnexions:Demo_Conditional_Compliation.cpp 4 23.2.3Denitions Denition23.7:conditionalcompilation AcompilerdirectivethatincludesorexcludeslinesofcodebasedonaBooleanexpression. 23.3Practice23:MoreArrays&CompilerDirectives 5 23.3.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Haveanexposuretomultidimensionalarrays. 3.Understandconditionalcompilationasatestingtechnique. 4.Whensuppliedwithtestdata,addconditionalcompilationlinestoanexistingC++sourcecode. 23.3.2MemoryBuildingActivities Linkto:MBA23 6 23.3.3Exercises Exercise23.1 Solutiononp.251. Answerthefollowingstatementsaseithertrueorfalse: 1.Veryfewarraysneedmorethanoneaxis. 2.Multidimensionalarraysusemultiplesquarebrackets,onesetperaxis. 3.Usingaagtoactivatedebugginglinesofcodehasbeenaroundsincethe1950s. 4 Seetheleat 5 Thiscontentisavailableonlineat. 6 Seetheleat

PAGE 258

250 CHAPTER23.23.MOREARRAYS&COMPILERDIRECTIVES 4.WithinC++wecanusetheconditionalcompilationcompilerdirectivestoimplementdebugginglineofcode. 23.3.4MiscellaneousItems Noneatthistime. 23.3.5LabAssignment 23.3.5.1CreatingaFolderorSub-FolderforChapter23Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_23withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 23.3.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_23a.cpp 7 23.3.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CompileandruntheLab_23a.cppsourcecodele.Understandhowitworks. CopythesourcecodeleLab_23a.cppnamingit:Lab_23b.cpp AddconditionalcompilationstatementssimilartothedemonstrationprogramusedintheConditional CompilationConnexionsmodule.Specicallyuse:157pennies,92nickels,23dimesand31quarters asyourtestdata. Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 23.3.6Problems 23.3.6.1Problem23aInstructions Givethreeexamplesintherealworldwheredatamightbestructuredintoamultidimensionalarray.One exampleandyoucan'tcountitisatheatreticketwhichmighthaveasection,rowandseatnumberonit. 7 Seetheleat

PAGE 259

251 SolutionstoExercisesinChapter23 SolutiontoExercise23.1p.249 Answers: 1.false 2.true 3.true 4.true

PAGE 260

252 CHAPTER23.23.MOREARRAYS&COMPILERDIRECTIVES

PAGE 261

Chapter24 24.OOP&HPC 24.1ObjectOrientedProgramming 1 24.1.1Discussion "Inproceduralprogramming,theprogrammerconstructsproceduresorfunctions,astheyarecalledin C++.Theproceduresarecollectionsofprogrammingstatementsthatperformaspecictask.Theprocedureseachcontaintheirownvariablesandcommonlysharevariableswithotherprocedures.Procedural programmingiscenteredontheprocedureorfunction." 2 Fordecadesstothroughthe1980smost programmingwastaughtas proceduralprogramming .Coupledwiththeimpositionofusingstandardized controlstructuresinthelate1960s,wehavewhatistypicallycalled modularstructuredprogramming Another,equallyvalidapproachtoprogrammingis object-orientedprogramming orOOP.Itwas introducedinthemid1980sandwaswidelyacceptedasaprogrammingapproachbytheearly1990s.The rstlanguagestointroduceOPPtothemasseswereC++andJava.Shortlyaftertheirintroduction,there wereAmericanNationalStandardsInstituteANSIstandardsestablishedforthoselanguages.Today,C++ andJavaarewidelyused. "Theprimarydierencesbetweenthetwoapproachesistheiruseofdata.Inaproceduralprogram, thedesigncentersaroundtherulesorproceduresforprocessingthedata.Theprocedures,implementedas functionsinC++,arethefocusofthedesign.Thedataobjectsarepassedtothefunctionsasparameters. Thekeyquestionishowthefunctionswilltransformthedatatheyreceiveforeitherstorageorfurther processing.Proceduralprogramminghasbeenthemainstayofcomputersciencesinceitsbeginningandis stillheavilyusedtoday. Inanobject-orientedprogram,abbreviatedOPP,thedesigncentersaroundobjectsthatcontainencapsulatethedataandthenecessaryfunctionstoprocessthedata.InOOP,theobjectsownthefunctions thatprocessthedata." 3 "Object-orientedprogramming ::: iscenteredontheobject.Anobjectisaprogrammingelementthat containsdataandtheproceduresthatoperateonthedata.Theobjectscontain,withinthemselves,both theinformationandtheabilitytomanipulatetheinformation." 4 Tohelpcomplicatethepicture,theC++programminglanguagecanbeusedandisusedtowriteeither aproceduralprogrammodularstructuredprogramoranobject-orientedprogram.Someitemsusedby thosewritingproceduralprogramsinC++areinfactobjects.Examplesinclude: 1 Thiscontentisavailableonlineat. 2 TonyGaddis,JudyWaltersandGodfreyMuganda, Starting Out with C++ Early Objects Sixth EditionUnitedStatesof America:PearsonAddisonWesley,200822. 3 BehrouzA.ForouzanandRichardF.Gilberg, Computer Science A Structured Approach using C++ Second EditionUnited StatesofAmerica:ThompsonBrooks/Cole,2004156. 4 TonyGaddis,JudyWaltersandGodfreyMuganda, Starting Out with C++ Early Objects Sixth EditionUnitedStatesof America:PearsonAddisonWesley,200822. 253

PAGE 262

254 CHAPTER24.24.OOP&HPC 1.Standardinputandoutputitemsof:coutandcin;example:cout.setfios::xed 2.Strings;calculatingthelengthwith:identier_name.length 3.Fileinput/output;example:inData.openlespec,ios::in Objectsareimplementedwitha"class"datatype;whichisacomplexorderiveddatatype.Implementation detailswillnotbepresentedinthemodule. 24.1.2Transition Manystudentswilllearnmodularstructuredprogrammingbeforelearningobject-orientedprogramming. Thecommonwayofteachingprogrammingfundamentalsistocoverthemordividethemintothreecourses, usuallycoveredinthisorder: 1.Modularstructured 2.Object-oriented 3.Datastructures Thefollowingitemslearnedinmodularstructuredprogrammingowintothelearningofobject-oriented programming: 1.Thestandardandcomplexdatatypesarethesame 2.Theoperatorsarethesame,thusdatamanipulationisthesame 3.Thecontrolstructuresarethesame 4.Conceptsofdocumentationandmakingcodereadablearethesame 5.Theuseoftestdatatoverifylogicalthinkingandprogramresultsissimilar 24.1.3Denitions Denition24.1:proceduralprogramming Akamodularstructuredprogramming. Denition24.2:objectoriented Aprogrammingapproachthatencapsulatesdatawithfunctions. 24.2UnderstandingHighPerformanceComputing 5 24.2.1PrefaceJune2,2009 Thismodulewascreatedasanentryforthe 2008-'09OpenEducationCup:HighPerformance Computing competition.ThecompetitionwassupervisedbyDr.JanErikOdegard,ExecutiveDirector oftheKenKennedyInstituteforInformationTechnologyatRiceUniversity.Itwassubmittedtothe "ParallelAlgorithmsandApplications"categoryandspecicallydesignedasanintroductiontothesubject targetingintermediategradeschoolstudentstocollegiateundergraduateswhohavelittleknowledgeofHigh PerformanceComputingHPC. Thosewhoreviewedtheentriesforthecompetitionmadesomesuggestionsforimprovementandmost havebeenincorporatedintothisrevisededitionofthemodule.Asalways;mythankstothemandallothers whomakesuggestionsforimprovingeducationalmaterials. KennethLeroyBusbee 5 Thiscontentisavailableonlineat.

PAGE 263

255 24.2.2IntroductiontoHighPerformanceComputing Groupingmultiplecomputersormultiplecomputerprocessorstoaccomplishataskquickerisreferredto as HighPerformanceComputing HPC.Wewanttoexplainhowthisisaccomplishedusingparallel programmingalgorithmsorconcepts. 24.2.2.1TheShiftfromaSingleProcessortoParallel Wearegoingtostartourexplanationbygivingtwosimpleexamples. Example24.1 Aftereatingallyoucan,youtossyourchickenlegboneoutofthecarwindowshameonyoufor trashingupthehighway,butinshortorderanantndsyourtossedchickenbone.Onesingleant couldbiteotheleftoverontheboneandtransportittothecolony,onebiteatatime;but,it mighttakehim1wholedayhoursofwork.But,whatifhegetshelp?Hesignalssomebuddies andbeingasmallcolonyofantstheyallocateatotalof10antstodothetask.Tentimesthe workerstakeonetenththetime.Thetenantsdothetaskin2hoursand24minutes. Itossanotherboneoutthewindow.Anantndsitandthecolonyallocates50antstodothe taskofpickingtheboneclean.Inlessthan30minutes.8tobeexactthe50antsworkingin parallelcompletethetask. Example24.2 Onepaintermighttake8hourstopainttheexteriorofanaveragesizedhouse.But,ifhecan putacrewof10paintersworkingsimultaneouslyorinotherwordsinparallelittakesonly48 munities.Whataboutacrewof50paintersassumingthattheycandoworkandnotgetinthe wayofeachother;wellhowaboutlessthan10minutes.6tobeexact. Nowlet'smakesureweunderstandthatthesameamountofworkwasdoneintheexamplesgiven.Thework wasonlycompletedinashorteramountoftimebecauseweputmoreworkersonthetask.Notalltaskscan bedividedupinthisway,butwhenitcanbedividedbetweenmultipleworkers,wecantakeadvantageof theworkersdoingtheirsubpartofthetaskinparallel.Let'slookatanotherexample. Example24.3 IwanttodrivefromHouston,TexastoDallas,Texas;adistanceofabout250miles.Foreasy calculationslet'ssayIcantravel50milesinonehour.Itwouldtakeme5hours.Well,Icould dividethetaskbetween5carsandhaveeachcartravel50milesandarriveinDallasin1hour. Right? Well,wrong.ThetaskofdrivingfromHoustontoDallascannotbedividedintotasksthatcanbedonein parallel.ThetaskcanonlybedonebyonepersondrivinginalinefromHoustontoDallasin5hours.Iused theword"line"becauseithelpsconnectustotheword: linear .Alineartaskcannotbebroken-upinto smallertaskstobedoneinparallelbymultipleworkers.Withinthecomputerworld,thewordassociated withlinearconceptis sequentialprocessing .ImustdriveonemileatatimeinsequencetogettoDallas. Ournaturaltendencyistosharetheworkthatistoworkinparallelwheneveritispossible.Asagroup wecanaccomplishmanytasksthatcanbedoneinparallelinlesstime. 24.2.2.2TheBirthofComputersA"Parallel"toCentralProcessingUnitCPUStory ENIAC,shortforElectronicNumericalIntegratorAndComputer,wastherstgeneral-purposeelectronic computerJuly1946.ItwastherstTuring-complete,digitalcomputercapableofbeingreprogrammedto solveafullrangeofcomputingproblems.ENIAChadtwentyten-digitsignedaccumulatorswhichusedten's complementrepresentationandcouldperform5,000simpleadditionorsubtractionoperationsbetweenany ofthemandasourcee.g.,anotheraccumulator,oraconstanttransmittereverysecond.Itwaspossible toconnectseveralaccumulatorstorunsimultaneously,sothepeakspeedofoperationwaspotentiallymuch higherduetoparalleloperation.ENIACfromWikipedia

PAGE 264

256 CHAPTER24.24.OOP&HPC Oftennotunderstoodbymanytoday,therstcomputerusedbase10arithmeticintheelectronicsand wasa parallelprocessing machinebyusingseveralaccumulatorstoimprovethespeed.However,thisdid notlastforlong.Duringitsconstruction: TheFirstDraftofaReportcommonlyshortenedtoFirstDraftontheEDVACElectronicDiscrete VariableAutomaticComputerwasanincomplete101pagedocumentwrittenbyJohnvonNeumannand distributedonJune30,1945byHermanGoldstine,securityocerontheclassiedENIACproject.It containstherstpublisheddescriptionofthelogicaldesignofacomputerusingthestored-programconcept, whichhascometobeknownasthevonNeumannarchitecture.FirstDraftofaReportontheEDVAC fromWikipedia ThevonNeumannarchitectureisadesignmodelforastored-programdigitalcomputerthatusesa [central]processing[unit]andasingleseparatestoragestructuretoholdbothinstructionsanddata.Itis namedafterthemathematicianandearlycomputerscientistJohnvonNeumann.Suchcomputersimplement auniversalTuringmachineandhaveasequentialarchitecture.VonNeumannarchitecturefromWikipedia VonNeumannalsoproposedusingabinarybase2numberingsystemfortheelectronics.Oneof thecharacteristicsofthevonNeumannarchitecturewasthetradeoofmultipleprocessorsusingbase10 electronicstoasinglecentralprocessorusingbase2ordigitalelectronics.Tocomparetoourantexample, theideawastouseonerealfastantversus10slowants.Ifonerealfastantcando1,000tasksinanhour; itwouldbemorepowerfulbeabletodomoretasksthan10antsdoing10tasksanhourortheequivalent of100tasksperhour. Therestishistorymostcommerciallybuiltcomputersforabouttherstfortyyearsto1991 followedthevonNeumannarchitecture.Theelectronicengineerskeepbuildingmorereliableandfaster electronics.Fromvacuumtube,totransistor,tointegratedcircuittowhatwecalltoday"chip"technology. Thistransformationmadecomputersbreakdownlessfrequentlytheyweremorereliable,physicallysmaller, needinglesselectricpowerandfaster.Personalcomputerswereintroducedinthelate1970'sandwithinten yearsbecamemorecommonlyavailableandused. Oneshortcomingwasthatmostprogrammingeortsweretowardsimprovingthelinearorsequential wayofthinkingorsolvingaproblem.Afterall,thecomputerelectronicengineerswouldbemakingafaster computernextyear.Everyoneunderstoodthatthecomputerhadonlyone centralprocessingunit CPU. Right? 24.2.2.3TheNeedforPower Well,wrong.Computerscientistsandelectronicengineershadbeen experimenting withmulti-processor computerswithparallelprogrammingsince1946.Butit'snotuntilthe1980'sthatweseetherstparallelprocessingcomputersbuiltbyCrayandothercomputercompaniesbeingsoldascommercialbuilt computers.It'stimeforanotherexample. Example24.4 Thecircustravelingbytrainfromonecitytothenexthasanelephantthatdies.Theydecideto tosstheelephantothetrainshameonthemfortrashingupthecountryside,butinshortorder a"super"antfasterthanmostregularantsndstheelephant.Thisprojectismuchlargerthan yourtossedchickenbone.Onesingle"super"antcoulddothetaskbiteoapieceoftheelephant andtransportittothecolony,onebiteatatime;but,itmighttakeonewholeyear.Afterallthis requiresalotmoreworkthanachickenbone.But,whatifhegetshelp?Hesignalssomebuddies andbeingalargecolonyof"super"antstheyallocateatotalof2,190antstodothetask.Wow, theydevourtheelephantinsixhours. Thiselephantexampleisexactlywherethecomputerscientistshadarrived.Theelectronicengineerswere goingtocontinuetomakeimprovementsinthespeedofasinglecentralprocessingunitcomputer,but notsoonenoughtosatisfythe"needforpower"tobeabletosolvetasksrequiring immensecomputing power .Someofthenewtasksthatwouldrequireimmensecomputerpowerincludedthehumangenome project,searchingforoilandgasbycreating3dimensionalimagesofgeologicalformationsandthestudy ofgravitationalforcesintheuniverse;justtomentionafew.Thesolution:parallelprocessingtothe

PAGE 265

257 rescue.Basicallytheonlywaytogetthisimmensecomputerpowerwastoimplementparallelprocessing techniques.Duringthelate1970'sandearly1980'sscientistssawtheneedtoexploretheparallelprocessing paradigmmorefullyandthusthebirthofHighPerformanceComputing.Variousnationalandinternational conferencesstartedduringthe1980'stobeabletofurtherthecauseofHighPerformanceComputing.For exampleinNovemberof2008the"SC08"supercomputingconferencecelebratedtheir20 th anniversary. ThepredictingoftheweatherisagoodexamplefortheneedofHighPerformanceComputing.Usingthe fastestcentralprocessingunitcomputeritmighttakeayeartopredicttomorrow'sweather.Theinformation wouldbecorrectbut365dayslate.Usingparallelprocessingtechniquesandapowerful"highperformance computer",wemightbeabletopredicttomorrow'sweatherin6hours.Notonlycorrect,butintimetobe useful. 24.2.2.4MeasuringComputerPower Mostpeoplearefamiliarwiththegigahertzbillionsofinstructionspersecondmeasuretodescribehowfast asingleCPU'sprocessorisrunning.Mostmicrocomputersoftodayarerunningaround3GHzor3billion instructionsasecond.Although3billionsoundsfast,manyoftheseinstructionsaresimpleoperations. Supercomputingusesameasurementinvolvingoatingpointarithmeticcalculationsasthebenchmarkfor comparingcomputerpower."Incomputing, FLOPS or ops or op / s isanacronymmeaning FL oating point O perations P er S econd."andagain"OnMay25,2008,anAmericanmilitarysupercomputerbuiltby IBM,named'Roadrunner',reachedthecomputingmilestoneofonepetaopbyprocessingmorethan1.026 quadrillioncalculationspersecond."FLOPSfromWikipediaForthoseofusnotfamiliar: Example24.5:GettingaSenseofPower 3billionor3GHzis:3,000,000,000 1quadrillionor1pedaflopis:1,000,000,000,000,000 Youalsoshouldrealizethatyourpersonalcomputerisnotdoing3gigafolpworthofcalculations,but somethingslowerwhenusingtheFLOPSmeasurement. 24.2.2.5HighPerformanceComputingMadePersonal Ittookseveralyearsabout30togetcomputerstoapersonallevelto1981.Ittookabouttwenty yearslate1980'stopresent2009togetmulti-processorcomputerstothepersonallevel.Currentlyavailable tothegeneralpublicarecomputerswith"duocore"and"quadcore"processors.Inthenearfuture,micro computerswillhave8to16coreprocessors.Peopleask,"WhywouldIneedthatmuchcomputerpower?" Therearedozensofapplications,butIcanthinkofaleastoneitemthatalmosteveryonewants:highquality voicerecognition.That'sright!Iwanttotalktomycomputer.Tossyourmouse,tossyourkeyboard,no moretouchpadtalktoit. Again,oneshortcomingisthatmostprogrammingeortshavebeentowardsteachingandlearning thesequentialprocessingwayofthinkingorsolvingaproblem.Educatorswillnowneedtoteachand programmerswillnowneedtodevelopskillsinprogrammingusingparallelconceptsandalgorithms. 24.2.2.6Summary Wehavebouncedyoubackandforthbetweensequentialandparallelconcepts.Wecoveredournatural tendencytodoworkinparallel.Butwiththebirthofcomputerstheparallelconceptsweresettotheside andthecomputerindustryimplementedafastersingleprocessorapproachsequential.Weexplainedthe limitationsofsequentialprocessingandtheneedforcomputingpower.Thus,thebirthofHighPerformance Computing.Parallelprocessingcomputersaremigratingintoourhomes.Withthatmigration,thereisa greatneedtoeducatetheexistinggenerationanddevelopthenextgenerationofscientistsandprogrammers tobeabletotakeadvantageofHighPerformanceComputing.

PAGE 266

258 CHAPTER24.24.OOP&HPC 24.2.3LearnerAppropriateActivities HighPerformanceComputingisimpactinghowwedoeverything.Learning,working,evenourrelaxation andentertainmentareimpactedbyHPC.TohelpmorepeopleunderstandHPC,Ihavelistedappropriate activitiesbasedonwherealearnerisinrelationtotheirprogrammingskills. 24.2.3.1ComputerLiteracybutNoProgrammingSkills Wehaveprovidedtwocomputerprogramsthathelpstudentsseetheimpactofparallelprocessing.The rstisa"LineartoParallelCalculator"wherethestudententershowlongitwouldtakeonepersonto completeatask,askshowmanypeoplewillworkasagrouponthetask,thencalculateshowlongitwill takethegrouptocompletethetask.Thesecondisa"ParallelSpeedDemonstrationProgram"thatsimulates parallelprocessing.Itdisplaystothemonitortherst60factorialnumbersin60seconds,thenshowsasif 10processorsaredoingitin6seconds,thenasif100processorsaredoingitinlessthan1second.Bothare compiledandreadyforuseonanIntelCPUmachinecompiledforuseonWindowsOS. DownloadtheexecutablelefromConnexions:LineartoParallelCalculator 6 DownloadtheexecutablelefromConnexions:ParallelSpeedDemonstrationProgram 7 Aninterestingactivitywouldbetojoinagroupthatisusingthousandsofpersonalmicrocomputers viaInternetconnectionsforparallelprocessing.Severaldistributedprocessingprojectsarelistedinthe "FLOPS"articleonWidipedia.Onesuchgroupisthe"GreatInternetMersennePrimeSearch-GIMPS". AlinktotheGIMPSwebsiteis:http://www.mersenne.org/ 8 Anotheractivityisto"Google"somekeywords.Becareful-"Googling"canbeconfusingandoftencan bediculttofocusontheprecisesubjectthatyouwant. highperformancecomputing computationalscience supercomputing distributedprocessing 24.2.3.2LearningProgrammingFundamentals StudentslearningtoprogramthatarecurrentlytakingcoursesinModular/Structuredprogrammingand/or ObjectOrientedprogrammingmightwanttoreviewthesourcecodelesforthedemonstrationprograms listedabove.Theseprogramsdonotdoparallelprogramming,butthestudentcouldmodifyorimprove themtobetterexplainparallelprogrammingconcepts. Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inordertodownloadthesesource codeles. DownloadthesourcecodelefromConnexions:LineartoParallelCalculator 9 DownloadthesourcecodelefromConnexions:ParallelSpeedDemonstrationProgram 10 Anotherappropriateactivityisto"Google"someofthekeywordslistedabove.Withyourfundamental understandingofprogramming,youwillunderstandmoreofthematerialsthanthosewithnoprogramming experience.Youshouldgetasensethatparallelprogrammingisbecomingamoreimportantpartofa computerprofessional'sworkandcareer. Reviewthe"Top500SuperComputers"at:http://www.top500.org/ 11 Lookatthesourcecodelistingsprovidedinthenextsection,butremember,youcannotcompileorrun theseonyournormalcomputer. 6 Seetheleat 7 Seetheleat 8 http://www.mersenne.org/ 9 Seetheleat 10 Seetheleat 11 http://www.top500.org/

PAGE 267

259 24.2.3.3UpperDivisionUnder-GraduateCollegeStudents Thechallengeistotryparallelcomputing,notjusttalkaboutit. DuringtheweekofMay21sttoMay26thin2006,thisauthorattendedaworkshoponParalleland DistributedComputing.TheworkshopwasgivenbytheNationalComputationalScienceInstituteand introduced parallelprogramming usingmultiplecomputersagroupofmicrocomputersgroupedor clusteredintoasuper-microcomputer.Theconferenceemphasizedseveralimportantpointsrelatedtothe computerindustry: 1.Duringthepastfewyearssuper-microcomputershavebecomemorepowerfulandmoreavailable. 2.Desktopcomputersarestartingtobebuiltwithmultipleprocessorsorcoresandwewillhave multipleto30coreprocessorswithinafewyears. 3.Useofsuper-microcomputingpoweriswidespreadandgrowinginallareas:scienticresearch, engineeringapplications,3Danimationforcomputergamesandeducation,etc. 4.Thereisashortageofeducators,scienticresearchers,andcomputerprofessionalsthatknowhowto manageandutilizethisdevelopingresource.Computerprofessionalsneededinclude:Techniciansthat knowhowtocreateandmaintainasuper-microcomputer;and Programmersthatknowhowto createcomputerapplicationsthatuseparallelprogrammingconcepts Thislastitemwasemphasizedtothoseofyoubeginningacareerincomputerprogrammingthatasyou progressinyoureducation,youshouldbeawareofthechangingnatureofcomputerprogrammingasa profession.Withinafewyears allprofessionalprogrammerswillhavetobefamiliarwithparallel programming Duringtheconferencethisauthorwroteaprogramthatsortsanarrayof150,000integersusingtwo dierentapproaches.Therstwaywaswithoutparallelprocessing.Whenitwascompiledandexecuted usingasinglemachine,ittook120.324secondstorunminutes.Thesecondwaywastoredesignthe programsopartsofitcouldberunonseveralprocessorsatthesametime.Whenitwascompiledand executedusing11machineswithinaclusterofmicro-computers,ittook20.974secondstorun.That's approximately6timesfaster.Thus, parallelprogrammingwillbecomeanecessitytobeableto utilizethemulti-processorhardwareofthenearfuture. AdistributedcomputingenvironmentwassetupinanormalcomputerlabusingaLinixoperating systemstoredonaCD.AfterbootingseveralcomputerswiththeCD,thecomputerscancommunicatewith eachotherwiththesupportof"MessagePassingInterface"orMPIcommands.Thismodelknownasthe BootableClusterCDBCCDisavailablefrom: BootableClusterCDUniversityofNorthernIowaat:http://www.bccd.net/ 12 Thesourcecodelesusedduringtheaboveworkshopweremodiedtoaversion8,thusan8isinthe lename.Thenon-parallelprocessing"super"codewasnamed:nonps8.cppwiththeparallelprocessing "super"codenamed:ps8.cppNote:Theparallelprocessingcodecontainssomecommentsthatdescribe thatpartofthecodebeingrunbyamachineidentiedasthe"SERVER_NODE"withapartofthecode beingrunbythe10othermachinestheClients.Theclientmachinescommunicatecriticalinformationto theservernodeusing"MessagePassingInterface"orMPIcommands. Youmayneedtorightclickonthelinkandselect"SaveTargetAs"inordertodownloadthesesource codeles. DownloadthesourcecodelefromConnexions:nonps8.cpp 13 DownloadthesourcecodelefromConnexions:ps8.cpp 14 Twonotableresourceswithsupercomputerinformationwereprovidedbypresentersduringtheworkshop: OklahomaUniversitySupercomputingCenterforEducation&Researchat: http://www.oscer.ou.edu/education.php 15 12 http://www.bccd.net/ 13 Seetheleat 14 Seetheleat 15 http://www.oscer.ou.edu/education.php

PAGE 268

260 CHAPTER24.24.OOP&HPC ContraCostaCollegeHighPerformanceComputingat:http://contracosta.edu/hpc/resources/presentations/ 16 Youcanalso"Google"thetopic'skeywordsandspendseveraldaysreadingandexperimentingwith HighPerformanceComputing. Considerreviewingthe"EducatorResources"linksprovidedinthenextsection. 24.2.4EducatorResources TherearemanysitesthatprovidematerialsandassistancetothoseteachingthemanyaspectsofHigh PerformanceComputing.Afewofthemare: ShodorANationalResourceforComputationalScienceEducationat:http://www.shodor.org/home/ 17 CSERDComputationalScienceEducationReferenceDeskat:http://www.shodor.org/refdesk/ 18 NationalComputationalScienceInstituteat:http://www.computationalscience.org/ 19 AssociationofComputingMachineryat:http://www.acm.org/ 20 SuperComputingEducationat:http://sc09.sc-education.org/about/index.php 21 24.2.5SimpleDenitions Denition24.3:highperformancecomputing Groupingmultiplecomputersormultiplecomputerprocessorstoaccomplishataskinlesstime. Denition24.4:sequentialprocessing Usingonlyoneprocessorandcompletingthetasksinasequentialorder. Denition24.5:parallelprocessing Dividingataskintopartsthatcanutilizemorethanoneprocessor. Denition24.6:centralprocessingunit Theelectroniccircuitrythatactuallyexecutescomputerinstructions. Denition24.7:parallelprogramming Involvesdevelopingprogramsthatutilizeparallelprocessingalgorithmsthattakeadvantageof multipleprocessors. 24.3Practice24:OOP&HPC 22 24.3.1LearningObjectives With100%accuracyduringa:memorybuildingactivity,exercises,labassignment,problems,ortimed quiz/exam;thestudentisexpectedto: 1.Denethetermsonthedenitionsaslistedinthemodulesassociatedwiththischapter. 2.Gainanexposuretoobject-orientedprogramming. 3.Gainanexposuretohighperformancecomputing. 4.Givengeneralinstructions,writetheC++codeforaprogramthatincludesageneralreviewofthe textbook/collection/course. 16 http://contracosta.edu/hpc/resources/presentations/ 17 http://www.shodor.org/home/ 18 http://www.shodor.org/refdesk/ 19 http://www.computationalscience.org/ 20 http://www.acm.org/ 21 http://sc09.sc-education.org/about/index.php 22 Thiscontentisavailableonlineat.

PAGE 269

261 24.3.2MemoryBuildingActivities Linkto:MBA24 23 24.3.3Exercises Exercise24.1 Solutiononp.263. Answerthefollowingstatementsaseithertrueorfalse: 1.Proceduralprogrammingandobject-orientedprogrammingcannotbedonewiththesame compiler/IDE. 2.Object-orientedprogrammingencapsulatesdataandfunctions. 3.HighPerformanceComputingisanewtopiconthecomputerscene. 4.TheconceptsandexamplesofHighPerformanceComputerarediculttoexplain. 5.Allprogrammerswillneedtoknowaboutparallelprogramminginthenearfuture. 24.3.4MiscellaneousItems Noneatthistime. 24.3.5LabAssignment 24.3.5.1CreatingaFolderorSub-FolderforChapter24Files Dependingonyourcompiler/IDE,youshoulddecidewheretodownloadandstoresourcecodelesfor processing.Prudencedictatesthatyoucreatethesefoldersasneededpriortodownloadingsourcecodeles. Asuggestedsub-folderforthe BloodshedDev-C++5compiler/IDE mightbenamed: Chapter_24withinthefoldernamed:Cpp_Source_Code_Files Ifyouhavenotdoneso,pleasecreatethefoldersand/orsub-foldersasappropriate. 24.3.5.2DownloadtheLabFiles Downloadandstorethefollowinglestoyourstoragedeviceintheappropriatefolders.Youmayneed torightclickonthelinkandselect"SaveTargetAs"inordertodownloadthele. DownloadfromConnexions:Lab_24_Narrative_Description.txt 24 24.3.5.3DetailedLabInstructions Readandfollowthedirectionsbelowcarefully,andperformthestepsintheorderlisted. CreateasourcecodelefollowingthedirectionsintheLab_24_Narrative_Description.txtle.Name it:Lab_24.cpp Buildcompileandrunyourprogram. Afteryouhavesuccessfullywrittenthisprogram,ifyouaretakingthiscourseforcollegecredit,follow theinstructionsfromyourprofessor/instructorforsubmittingitforgrading. 23 Seetheleat 24 Seetheleat

PAGE 270

262 CHAPTER24.24.OOP&HPC 24.3.6Problems 24.3.6.1Problem24aInstructions Describethefundamentaldierencesbetweenproceduralmodularstructuredprogrammingandobjectorientedprogramming. 24.3.6.2Problem24bInstructions ExplainwhyHighPerformanceComputingisneededtopredicttomorrow'sweather.

PAGE 271

263 SolutionstoExercisesinChapter24 SolutiontoExercise24.1p.261 Answers: 1.false 2.true 3.false 4.false 5.true

PAGE 272

264 CHAPTER24.24.OOP&HPC

PAGE 273

Chapter25 ReviewMaterials 25.1Review:FoundationTopicsGroup:1-5 1 25.1.1StrategyDiscussion Examsvarydependingonyourinstructor.Manywillusethefollowing: 1.Denitions 2.Self-gradingquestionsincludingtrue/false,multiplechoice,shortanswer,etc. 3.Problems Thematerialsinthistextbook/collectionhavecoveredtheseitemsattheendofeverychapterwithinthe Practice moduleforthatchapter.Wesuggestthefollowingtestpreparationstrategies: 1.Ifyourprofessoristestingthedenitionsandexpectingyoutohavethemmemorized,youshould reviewtheUsingtheFlashCardActivitywithintheStudyHabitsthatBuildtheBrainmodule withintheAppendixmaterials.PracticewritingyourdenitionsusingtheFlashCardActivityinthe MemoryBuildingActivitiesMBAsavailablewithinthe Practice modulesorintheMemoryBuilding Activitieswithinthis Review module. 2.DoaquickreviewofanyexerciseswithintheConnexionsmodulesorthe Practice modules.Also reviewquizzesorexamsthatyouhavetakenandpayspecialattentiontomakingsureyouunderstand whyyoumissedaquestion. 3.Ifyourprofessorhasindicatedthattheymightincludeafewoftheproblemspresentedwithinthe Practice modules,makesureyouhaveformulatedagoodanswerforeachproblem.Ifauthorized, collaboratewithotherstudentstoimproveyouranswerstotheproblems.Spendamoderateamount oftimereviewingeachproblemwithitsanswerbeforetheexam. 25.1.2MemoryBuildingActivities Linkto:MBAReview:FoundationTopicsGroup:1-5 2 25.1.3MiscellaneousItems Linkto:ManipulationofDataPart1 3 1 Thiscontentisavailableonlineat. 2 Seetheleat 3 Seetheleat 265

PAGE 274

266 CHAPTER25.REVIEWMATERIALS 25.2Review:ModularProgrammingGroup:6-9 4 25.2.1StrategyDiscussion Examsvarydependingonyourinstructor.Manywillusethefollowing: 1.Denitions 2.Self-gradingquestionsincludingtrue/false,multiplechoice,shortanswer,etc. 3.Problems Thematerialsinthistextbook/collectionhavecoveredtheseitemsattheendofeverychapterwithinthe Practice moduleforthatchapter.Wesuggestthefollowingtestpreparationstrategies: 1.Ifyourprofessoristestingthedenitionsandexpectingyoutohavethemmemorized,youshould reviewtheUsingtheFlashCardActivitywithintheStudyHabitsthatBuildtheBrainmodule withintheAppendixmaterials.PracticewritingyourdenitionsusingtheFlashCardActivityin conjunctionwiththeMemoryBuildingActivitiesMBAsavailablewithinthe Practice modulesor intheMemoryBuildingActivitieswithinthis Review module. 2.DoaquickreviewofanyexerciseswithintheConnexionsmodulesorthe Practice modules.Also reviewquizzesorexamsthatyouhavetakenandpayspecialattentiontomakingsureyouunderstand whyyoumissedaquestion. 3.Ifyourprofessorhasindicatedthattheymightincludeafewoftheproblemspresentedwithinthe Practice modules,makesureyouhaveformulatedagoodanswerforeachproblem.Ifauthorized, collaboratewithotherstudentstoimproveyouranswerstotheproblems.Spendamoderateamount oftimereviewingeachproblemwithitsanswerbeforetheexam. 25.2.2MemoryBuildingActivities Linkto:MBAReview:ModularProgrammingGroup:6-9 5 25.2.3MiscellaneousItems Noneatthistime. 25.3Review:StructuredProgrammingGroup:10-16 6 25.3.1StrategyDiscussion Examsvarydependingonyourinstructor.Manywillusethefollowing: 1.Denitions 2.Self-gradingquestionsincludingtrue/false,multiplechoice,shortanswer,etc. 3.Problems Thematerialsinthistextbook/collectionhavecoveredtheseitemsattheendofeverychapterwithinthe Practice moduleforthatchapter.Wesuggestthefollowingtestpreparationstrategies: 4 Thiscontentisavailableonlineat. 5 Seetheleat 6 Thiscontentisavailableonlineat.

PAGE 275

267 1.Ifyourprofessoristestingthedenitionsandexpectingyoutohavethemmemorized,youshould reviewthe"UsingtheFlashCardActivity"withinthe"StudyHabitsthatBuildtheBrain"module withintheAppendixmaterials.PracticewritingyourdenitionsusingtheFlashCardActivityin conjunctionwiththeMemoryBuildingActivitiesMBAsavailablewithinthe Practice modulesor intheMemoryBuildingActivitieswithinthis Review module. 2.DoaquickreviewofanyexerciseswithintheConnexionsmodulesorthe Practice moudles.Also reviewquizzesorexamsthatyouhavetakenandpayspecialattentiontomakingsureyouunderstand whyyoumissedaquestion. 3.Ifyourprofessorhasindicatedthattheymightincludeafewoftheproblemspresentedwithinthe Practice modules,makesureyouhaveformulatedagoodanswerforeachproblem.Ifauthorized, collaboratewithotherstudentstoimproveyouranswerstotheproblems.Spendamoderateamount oftimereviewingeachproblemwithitsanswerbeforetheexam. 25.3.2MemoryBuildingActivities Linkto:MBAReview:StructuredProgrammingGroup:10-16 7 25.3.3MiscellaneousItems Linkto:Animatedgifshowinganifthenelse 8 Linkto:Animatedgifshowingadowhileloop 9 Linkto:Animatedgifshowingawhileloop 10 Linkto:ManipulationofDataPart2 11 Linkto:ManipulationofDataPart3 12 25.4Review:IntermediateTopicsGroup:17-21 13 25.4.1StrategyDiscussion Examsvarydependingonyourinstructor.Manywillusethefollowing: 1.Denitions 2.Self-gradingquestionsincludingtrue/false,multiplechoice,shortanswer,etc. 3.Problems Thematerialsinthistextbook/collectionhavecoveredtheseitemsattheendofeverychapterwithinthe Practice moduleforthatchapter.Wesuggestthefollowingtestpreparationstrategies: 1.Ifyourprofessoristestingthedenitionsandexpectingyoutohavethemmemorized,youshould reviewthe"UsingtheFlashCardActivity"withinthe"StudyHabitsthatBuildtheBrain"module withintheAppendixmaterials.PracticewritingyourdenitionsusingtheFlashCardActivityin conjunctionwiththeMemoryBuildingActivitiesMBAsavailablewithinthe Practice modulesor intheMemoryBuildingActivitieswithinthis Review module. 2.DoaquickreviewofanyexerciseswtihintheConnexionsmodulesor Practice modules.Alsoreview quizzesorexamsthatyouhavetakenandpayspecialattentiontomakingsureyouunderstandwhy youmissedaquestion. 7 Seetheleat 8 Seetheleat 9 Seetheleat 10 Seetheleat 11 Seetheleat 12 Seetheleat 13 Thiscontentisavailableonlineat.

PAGE 276

268 CHAPTER25.REVIEWMATERIALS 3.Ifyourprofessorhasindicatedthattheymightincludeafewoftheproblemspresentedwithinthe Practice modules,makesureyouhaveformulatedagoodanswerforeachproblem.Ifauthorized, collaboratewithotherstudentstoimproveyouranswerstotheproblems.Spendamoderateamount oftimereviewingeachproblemwithitsanswerbeforetheexam. 25.4.2MemoryBuildingActivities Linkto:MBAReview:IntermediateTopicsGroup:17-21 14 25.4.3MiscellaneousItems Noneatthistime. 25.5Review:AdvancedTopicsGroup:22-24 15 25.5.1StrategyDiscussion Examsvarydependingonyourinstructor.Manywillusethefollowing: 1.Denitions 2.Self-gradingquestionsincludingtrue/false,multiplechoice,shortanswer,etc. 3.Problems Thematerialsinthistextbook/collectionhavecoveredtheseitemsattheendofeverychapterwithinthe Practice moduleforthatchapter.Wesuggestthefollowingtestpreparationstrategies: 1.Ifyourprofessoristestingthedenitionsandexpectingyoutohavethemmemorized,youshould reviewthe"UsingtheFlashCardActivity"withinthe"StudyHabitsthatBuildtheBrain"module withintheAppendixmaterials.PracticewritingyourdenitionsusingtheFlashCardActivityin conjunctionwiththeMemoryBuildingActivitiesMBAsavailablewithinthe Practice modulesor intheMemoryBuildingActivitieswithinthis Review module. 2.DoaquickreviewofanyexereciseswithintheConnexionsmodulesorthe Practice modules.Also reviewquizzesorexamsthatyouhavetakenandpayspecialattentiontomakingsureyouunderstand whyyoumissedaquestion. 3.Ifyourprofessorhasindicatedthattheymightincludeafewoftheproblemspresentedwithinthe Practice modules,makesureyouhaveformulatedagoodanswerforeachproblem.Ifauthorized, collaboratewithotherstudentstoimproveyouranswerstotheproblems.Spendamoderateamount oftimereviewingeachproblemwithitsanswerbeforetheexam. 25.5.2MemoryBuildingActivities Linkto:MBAReview:AdvancedTopicsGroup:22-24 16 25.5.3MiscellaneousItems Noneatthistime. 14 Seetheleat 15 Thiscontentisavailableonlineat. 16 Seetheleat

PAGE 277

Chapter26 Appendix 26.1AbbreviatedPrecedenceChartforC++Operators 1 An operator isalanguage-specicsyntacticaltokenoneormoresymbolsthatcausesanactiontobe takenononeormoreoperands.ThefollowingitemprovidesanabbreviatedlistofthoseC++operatorsthat aretypicallytaughtinaprogrammingfundamentalscoursethatteachesmodularstructuredprogramming concepts. Therstcolumnshowstheprecedencethehigherprecedenceis1oritgoesrstandoperatorsthat havethesameprecedencealsohavethesameassociativitytheassociativityisonlylistedonceforthe groupofoperators.Decrementistwominussigns,butsomewordprocessingsoftwareprogramsmighthave problemsprintingtwominussignsandconvertittoadoubledash.Insertiontwo < signsandextraction two > signsmightalsohaveprintingproblems.Theseprintingproblemsarenotedinthecommentswith emphasized text. PR OPERATOR NAME SYMBOLS COMMENTS ASSOICIATIVITY CONNEXIONS MODULE 1 functioncall LefttoRight m19145Section6.3 1 index [] akaarrayindex m21316Section18.2 2 classmember aperiod RighttoLeft m20796Section16.1 2 postxincrement ++ unary m20499Section14.1 2 postxdecrement unary, two minussigns m20499Section14.1 continuedonnextpage 1 Thiscontentisavailableonlineat. 269

PAGE 278

270 CHAPTER26.APPENDIX 3 indirection unary,aka dereference RighttoLeft m22152Section22.4 3 address & unary m22148Section22.1 3 unarypositive + unary,akaplus m20501Section16.2 3 unarynegative unary,akaminus m20501Section16.2 3 prexincrement ++ unary m20499Section14.1 3 prexdecrement unary, two minussigns m20499Section14.1 3 cast type unary m18744Section3.7 3 sizeof sizeoftype unary m18736Section9.2 3 logicalNOT unary m19847Section12.2 4 multiply LefttoRight m18706Section3.6 4 divide / m18706Section3.6 4 modulus % remainder m18706Section3.6 5 add + LefttoRight m18706Section3.6 5 subtract m18706Section3.6 6 insertion writing, two lessthan signs LefttoRight m18835Section5.2 6 extraction reading, two greaterthan signs m18835Section5.2 continuedonnextpage

PAGE 279

271 7 lessthan < LefttoRight m19549Section11.3 7 greaterthan > m19549Section11.3 7 lessthanor equalto < = m19549Section11.3 7 greaterthanor equalto > = m19549Section11.3 8 equality == equalto LefttoRight m19549Section11.3 8 inequality != notequalto m19549Section11.3 9 logicalAND && LefttoRight m19847Section12.2 10 logicalOR || LefttoRight m19847Section12.2 11 conditional ?: trinary LefttoRight m20811Section17.1 12 assignment = RighttoLeft m18725Section3.5 12 additionassignment += m18743Section4.4 12 subtractionassignment -= m18743Section4.4 12 multiplication assignment *= m18743Section4.4 12 divisionassignment /= m18743Section4.4 12 modulusassignment %= m18743Section4.4 13 sequenceor comma LefttoRight m18690Section9.4 Table26.1 26.2C++ReservedKeywords 2 Allprogramminglanguageshave"reservedwords".Thereareusuallylessthan50ofthesereservedwordsin anygivenprogramminglanguage.Theyarereservedbecausetheyhavebeenpre-assignedaspecicmeaning withinthatprogramminglanguage,thusthecompilerrecognizesthosewordstomeanaspecicthingor action.WithinC++thereservedwordsarealsoknownas"keywords". Programmersuseidentiernamesforavarietyofitems,toinclude:functions,variables,namedconstants, aliasnames,etc.But,theycan'tuseasidentiernamesthewordsthatare"reservedtothelanguage". 2 Thiscontentisavailableonlineat.

PAGE 280

272 CHAPTER26.APPENDIX FortheC++languageall"reservedkeywords"aretypedinlowercase.Thelistthatfollowsincludes theAmericanNationalStandardsInstituteANSIandtheInternationalOrganizationforStandardization ISOlistsofreservedwordsfortheC++programminglanguage.TheISOreservedwordsmaynotbe implementedinthecompilerthatyouareusing,howevertheymaybeadoptedinfuturereleasesofC++ compilers.Wisdomdictatestoavoidusingthematthispointsothattherewillnotbeaproblemcompiling yoursourcecodeinfuturereleasesofcompilers.TherehasbeennodistinctionmadeintheANSIorISO reservedwordlists.AsearchoftheInternetforC++reservedwordswillrevealseveraldierentlists.Some aremoreuniquetoaspeciccompiler.Somewillbeincompletebecausethelisthasbeenenlarged.The talbethatfollowsshouldworkforanybeginningprogrammingcourseusingC++.Thereservedkeywords are: and double not_eq throw and_eq dynamic_cast operator true asm else or try auto enum or_eq typedef bitand explicit private typeid bitor extern protected typename bool false public union break oat register unsigned case fro reinterpret-cast using catch friend return virtual char goto short void class if signed volatile compl inline sizeof wchar_t const int static while const-cast long static_cast xor continue mutable struct xor_eq default namespace switch delete new template do not this Table26.2 26.3ASCIICharacterSet 3 ASCIIstandsforAmericanStandardCodeforInformationInterchangepronounced"ask-key".Computers canonlyunderstandnumbers,soanASCIIcodeisthenumericalrepresentationofacharactersuchas'a' or'@'oranactionofsomesort.ASCIIwasdevelopedalongtimeagoandnowthenon-printingcharacters arerarelyusedfortheiroriginalpurpose.Therst32valuesto31andthelastvaluearethe non-printingcharacters. SeveralsoftwareproductscanbeusedtocreateanASCIItextle. 3 Thiscontentisavailableonlineat.

PAGE 281

273 NotepadwithinWindowsOSanditusesbydefaultthe.txtextension. MicrosoftWordbysavingtheleas'textonly'anditusesbydefaultthe.txtextension. IntegratedDevelopmentEnvironmentIDEcompliersformostprogramminglanguagesusuallysave sourcecodeasASCIItextlesbuttheywilluseanextensionthatdescribesthecontentofthetext le.Example:C++usuallyuses.cppastheextension. ThefollowingweblinksprovidemoreinformationandtableslistingtheASCIICharacterSet: http://asciiset.com/ 4 http://www.asciitable.com/ 5 http://en.wikipedia.org/wiki/ASCII 6 26.4ShowHideFileExtensions 7 Bydefault,leextensionsforknownletypesarehiddeninWindowsXPandWindowsVista.However, youcanchangethissettingsothatleextensionsareshownforles.Beingabletoseeleextensionscan beveryhelpfulforstudentstakingcomputercoursesbecausethosecourseinstructionsoftenrefertole extensions. Thefollowingweblinksprovideinstructionsforshowingorhidingleextensions. 26.4.1WindowsXP http://www.leinfo.net/help/windows-show-extensions.html 8 26.4.2WindowsVista http://windowshelp.microsoft.com/Windows/en-US/Help/a0b4607a-6fa8-42ab-aef67418183389da1033.mspx 9 26.5AcademicorScholasticDishonesty 10 26.5.1Introduction Therelationshipbetweenfacultyandstudentshasalwaysbeenoneofopenandhonestcommunication.The facultymembercarriestheresponsibilityofpresentingcoursematerialsviareadingassignments,lectures, labs,etc.Thestudentistolearnandunderstandthesematerials.Additionally,thefacultymembersemploy variousmethodstoassessthestudent'smasteryofthecoursematerials.Frequentlythisisdoneviaquizzes, tests,writingassignments,thecompletionoflabmaterials,etc.Academicdishonestysometimescalled "ScholasticDishonesty"istheviolationofthattrust. Cheatingonquizzesandtestsaswellasplagiarismisusuallywellunderstoodbystudentsbeforearriving atthecollegiatelevelofeducation.Mostcollegesincludeadequateexplanationintheirstudenthandbook explainingwellwhatconstitutescheatingonexamsandplagiarism.Academicdishonestyoftencarriessome stipenalties.Usually,thestudentreceivesthegradeof"F"fromtheprofessorinthecourseinwhichheis enrolled.Thestudentmightbeexpelledfromalloftheirclassesforwhichtheyarecurrentlyenrolled"F" inallofyourclassesandexpelledfromtheinstitutionmaynotregisterforclassesinthefuture.Sounds harsh,butitisaviolationofthe bondoftrust betweenthestudentandtheeducationalinstitution. 4 http://asciiset.com/ 5 http://www.asciitable.com/ 6 http://en.wikipedia.org/wiki/ASCII 7 Thiscontentisavailableonlineat. 8 http://www.leinfo.net/help/windows-show-extensions.html 9 http://windowshelp.microsoft.com/Windows/en-US/Help/a0b4607a-6fa8-42ab-aef6-7418183389da1033.mspx 10 Thiscontentisavailableonlineat.

PAGE 282

274 CHAPTER26.APPENDIX 26.5.2Collusion Anothercategoryofacademicdishonestyiscollusionwhichistheunauthorizedcollaborationwithanother personinpreparingwrittenworkincludinglabassignmentsoeredforcreditcountingtowardsyour gradecalculation.Tobetterunderstandcollusion,studentsneedtorealizethataspartofthelearning andevaluationofthatlearning,manyprofessorsusegroupprojects;adirectedorauthorizedcollaboration. Oftenstudentsareencouragedtoformstudygroupstohelpdiscussthecoursematerialsthusimprovingthe learningprocess.Theseauthorizedandsometimesdirectedactivitiesarenotcollusion. Thefollowingdiscussionistohelpthestudentunderstandcollusionunauthorizedcollaborationwith specicreferencetocoursesthatusecomputers.Thisisnotanallinclusivelist,butwillcoverthecommon situationsthatfacultyhaveencounteredovertheyears.Unlessyourspecicprofessorinformsyoudierently, youaretoassumethatthefollowingitemsdiscussedarecollusion. 26.5.3TypeitYourself Labassignmentsaretobeyourownpersonaltypingeorts.Thatisyouaretotypethemormakethe modicationsyourselftothelesdocuments,spreadsheets,databases,programmingsourcecode,etc.If yourcourseisaprogrammingsubject,youaretorunthesourcecodeleonyourcompiler,makingcorrections asneedtocompletethelabassignment.Ifthedirectionsforanassignmentincludestartinganewlethen don'tuseanexistingleandmodifyittocompletetheassignment. Unlessspecicallyauthorizedby yourprofessor,studentsshouldnotcompletecomputerizedcourseworkasateamorgroup andthensharethenalcompletedproduct. Studentshavesaidthattheyworkedasateamorgroupandthatallparticipatedandalllearnedthe materials.Don'ttrythisexcusebecauseprofessorsdon'tbuyit.Hereistheproblem:Partofthelearning processisinyoudoingityourself.Example:Iasktwostudentstomakemesomepancakesforbreakfast;I expecttwoindividuallypreparedplatesofpancakesonefromeachofthemformybreakfast.Theprofessor reallydoesnotwanttoeattwoplatesofpancakesor50to100platesofpancakes,dependingonhowmany studentstheyareteaching,butpartofyourdirectedlearningactivityforthecourseistodemonstratethat youcanmakepancakesnotwatchsomeoneelsemakepancakesorparticipateasagrouptomakepancakes. 26.5.4ControlAccesstoYourFiles Controllingthelesyoucreateoraredirectedtomodifymeansthatotherswillnothaveaccesstocopy yourwork.Inotherwords,don'tshareyourles. Studentshavesaidthattheysharedthelesotheytheotherstudentcouldseehowthecompleted assignmentshouldlook.Don'ttrythisexcusebecauseprofessorsdon'tbuyit.Hereistheproblem:When yousharetheleyoushareyourtypingeortsoryouroriginalworkandyoureortstocreatethatoriginal work.Backtoourpancakeexample:"Ionlygavetheotherstudentaplateofcompletedpancakes,sohe couldseewhattheendproductshouldbe."Alltheotherstudentdoesisaddsomeblueberriesandwhip cream.Ifastudentmakesminormodicationstoyourworkchangesthespotswhereyournameistohis nameandturnsitinashisworkyouwillbeincludedinthechargeofacademicdishonesty. Unless specicallyauthorizedbyyourprofessor,don'tshareanylesthatyoucreateormodifywith anotherstudentever,notnowandnotinthefuture. Herearetwosuggestionsforcontrollingaccesstoyourles: Whenusingacoursedeliverysoftwareproductorlearningsystem,suchasBlackBoradVista, don'tgive anotherpersonyourpassword .Withthepassword,theywillhaveaccesstoyoursubmittedassignments includingthelesthatyoucreated. Don'tleaveyourlesonamachinewhereothersmayhaveaccesstothem.Ifmultiplestudentsare usingorhaveaccesstothesamemachineoftenhappenswithstudentslivinginthesamehousehold husband/wife,siblingsorroommatesorinanon-campuscoursewheremanystudentswillhaveaccessto themachine storeyourlesonaashdrive .Physicallycontrolwhogetsaccesstoyourashdrive.

PAGE 283

275 26.5.5AskforaClaricationoftheCollaboration Ifyouhaveanyquestionaboutanactivitythatmightbeconstruedasunauthorizedcollaboration,askyour professor.Theywillprovideclaricationanddirectiontoyouabouttheactivity. Studentshavesaidthattheydidnotunderstandorthinkthatitwasunauthorizedcollaboration.Don't trythisexcusebecauseprofessorsdon'tbuyit.Hereistheproblem:Wecan't,andwon'tlisteveryminor wayinwhichstudentscancollude. Theburdenisforyoutoaskforanyclaricationforthespecic coursefromyourprofessor. Don'tassumethatwhatanotherinstructorallowedinanothercoursewill beallowedbythisprofessorinthiscourse. 26.5.6DetectingAcademicDishonesty Professorsweren'tbornyesterday.Thefacultymembersofmostinstitutionshaveindividuallyyearsand collectivelythousandsofyearsatunderstandingacademicdishonesty.Cheatingontests,plagiarismand collusionarenotnewtous.Weshareourexpertisewitheachotheratdetectingacademicdishonesty. Additionally,theyearsoftechnicalcomputerexperienceofprofessorswhoteachusingcomputersinlab settingsisoftenastounding. Studentshavesaidthattheydidnotthinktheycouldbedetectedorthatacademicdishonestycouldnot beproved.Don'ttrythisapproachbecauseprofessorsbelievethattheyareslightlysmarter.Actually,we knowthatwearealotsmarter.Itamazesusthatsomestudentsdon'trealizethatprofessorsareaformidable force. Don'tgamblethatyoucanbeatusatthe"AcademicDishonestyGame". Pleasedon'ttake thisasachallengeanduseitasanexcusetoseeifyoucanbeacademicallydishonestandnotgetcaught. Wearewarningyou,notchallengingyou. 26.5.7Summary Theethicsofacademichonesty;thereisabondoftrustthatwhateverthestudentdoesinrelationship totheevaluationprocessaretheirownworkandeorts. Collusionistheunauthorizedcollaborationofstudentsonworksubmittedforevaluation. Firstdirective:Typeifyourself Seconddirective:Don'tshareyourles Seekclaricationfromyourprofessorifyouhaveanydoubtthatthecollaborativeactivitymightbe consideredcollusion. Professorsareverycapableatdetectingacademicdishonesty. 26.6SuccessfulLearningSkills 11 26.6.1RealizetheTimeCommitment Collegecomputercoursesoftenarelistedinthecatalogofcourseswithbothlectureandlabhours.But unlikethenaturalandbiologicalscienceschemistry,physicsandbiologythatmustmeetinaspeciclab 11 Thiscontentisavailableonlineat.

PAGE 284

276 CHAPTER26.APPENDIX roomdesignedforthosecourses,studentscanusuallycompletetheirlabportionsatavarietyoflocations thecollege'scomputerlab,home,work,publiclibrary,friend'shouse,etc.. Thenormalruleofthumbis1to1.5hoursoutofclassstudyingforeveryhourinclassandforcomputer coursesthisnormallymeansboththelectureandlabhours.Studentswithlearningdisabilitiesorthosewhose primarylanguageisnotEnglishwillwanttoplanformorestudytimeandshouldusealargerratio.Thus, youshouldcalculatetheweeklyhoursofcommitmentneededforacoursedependingonyourcircumstances. Example: Ifastudentistakinga4credithourcomputercoursethatthecollegecatalogsayscontainsacombination of6hoursaddingyourlectureandlabhoursduringaregular16weeksemester;theweeklyclassroomand studytimeforthatcoursewouldbe12to15hoursaweek. Butmanystudentstakecoursesatafasterpacebyeithertakingacoursebetweensemestersinavery concentratedmode,startingacourseaftertheregularstartofasemesterorduringthesummer.Tocalculate theweeklystudytimeneededyouwillneedtocalculatethetotalregularsemesterinstructionaltimeand dividebythenumberofweeksinthefasterpacedelivery.Example: Our4credithourcourseistobetakenduringasummertermthathas9weeksofinstructiontime.The totalregularsemestertimewouldbe15timesthenormalsemestercommitmentto225hours.Dividing itby9wouldmean20to25hoursperweek. 26.6.2UnderstandYourCapacitytoConcentrate Youcannotexpecttospendlongperiodsoftimeworkingoncomputercoursematerials.After3to4hours ofworkingoncoursematerials,yourabilitytolearndropssignicantlyandformosttonearzero.This problemiscompoundedbythenatureofthematerialwhichiscumulativeinnature.Thismeansthatyou mustunderstanditemabeforeyoutrytolearnitemb.Allofthemathandsciencescoursesofstudyareof thisnature. 26.6.3PlanRegularStudyTimes Thecombinationofthetimecommitmentandyourabilitytoconcentrateleadstotheconclusionthatyou cannotcramyourstudytimeintoaweek-endofconcentratedstudy.Youmustbreakupyourstudytime into3to4hourstudyperiodsdoingonlyonestudyperiodperday.Youmustestablisharegularroutine foreachweek.Studentstakingaregularsemestercourseon-campuswillcounttheirclasslectureandlab timeandplan2to3additionalstudyperiods. Iftakingacourseviadistanceeducation,studentsneedtoplanforallofthecoursetime,thusduringa regularsemesterterm,our4credithourcourseexamplewouldrequire3to4studyperiodswith3to4hours foreachstudyperiodperweek.Iftakingthecourseat fasterpace weeksummertermyouwillneedto schedulemorestudytimes.Thismaymeana 3to4hourstudyperioddailyfor6daysaweek with onlyonedayoasadayofrest. Youneedtostayontopofacoursetosuccessfullycompleteit.Pacingyourselfwithmultiplestudy timesallowsforeectivelearning.Studentswhoprocrastinateuntilclosetoanexamandthentrycramming throughcoursematerialsarerarely"A"students. 26.6.4LearningRequiresVarietyandRepetition Varietycomesinmanyformsandincludeslecture,labassignments,studyingtextbooks,multi-mediamaterials,quizzes,writingaresearchpapers,learningactivitiessuchasgroupdiscussions,crosswordpuzzles,ash cards,etc.Thisvarietyactuallyhelpsourbraintounderstandandbuildmemory.Inadditiontovariety, repetitionexposureovermultiplestudyperiodsisessentialforourbrainstobeabletolearnandrecall thecoursematerials.Again,thisunderstandingandrecallareessentialtocoursesthatrequirecumulative learningyoumustunderstanditemabeforeyoucanlearnitemb. Textbooksandprofessorsbreak-upcoursematerialsintochaptersorlearningmodulesoftenwithlearning objectivesrstandreviewitemsattheendofeachunit.Eachchapterormodulemighthaveanyofthe

PAGE 285

277 abovementioneditems.Butdoingthingsandstudyaredierent.Youcan'tjustshowuptoclassandlisten, youcan'tjustreadstu,youneedtostudy.Studyrequiresavarietyofactivities.Askyourself: Doyouunderstandeachlearningobjective? Canyouexplainorformulateananswerforeachlearningobjective? Ifyoudidnotunderstandthereadingmaterials,didyoure-readit? Dothereviewitemsespeciallyquestions. Takelecturenotes. Dothelecturenotesorhandoutsgiveyouabetterunderstandingthanthetextbook? Oftentheproblemsorlabassignmentsaretobestudiedinconjunctionwithandreinforcethestudy materials.Haveyoutriedtodoandunderstandtheproblemsorlabassignments? Arethereanylearningactivitiesavailableandifyes,didyoudothem. Didyouconsiderusing3x5cardstostudydenitionsandvocabulary? Didyoureviewthelearningobjectivesbeforetakinganyquizzes? Ifthequizzesarecomputerized,didyoustudyyourquizresults? Afterreviewingquizresultsandre-study,didyouretakethequizagainifavailable? Allofthisrequirestimeandeortonyourpartasthestudentinanycoursedistanceeducationoroncampus.Youneedseveralstudyperiodsaweektolearnthematerialsinanycourse.Thepurposeofaquiz isforyoutoselfassessyourunderstandingofthematerials.Ifyourlearningisnotcomplete, changeor modifyyourlearninghabits 26.6.5InteractwiththeOtherStudents Inanormalclassroomstudentsinteractwitheachother.Theyoftenformstudygroupswithotherstudents andmeetregularlytohelpeachotherstudymaterials.Theseinteractionsinmostcasesareessentialtothe learningprocess.Ifyouronlyinteractionisbyprivateconversationorprivateemailwiththeinstructor,you arenotfullyparticipatinginthecourse.Fordistanceeducationstudents,mostlearningsystemssuchas BlackboardVistaprovideseveraltoolstocreatethisinteraction.Theytypicallyincludeannouncements, discussionlist,emailandchattools. 26.6.6Don'tProcrastinateandDon'tGetBehind Whatshouldyoudoifyougetbehind?Plan regularstudyperiods. Thelackofregularstudyperiods ismostlikelythereasonforwhyyougotbehind.Planwhenyouwilldo extrastudyperiods inorderto catchup. 26.6.7AttendClassandTakeNotes Takinglecturenotesandbeingabletoreviewthosenotelaterwhenyouarestudyingprovidesvarietythat isneededtolearnmaterial.Justwritingthenotesdownmoreactivelyengagesthebrain,becauseyouare listeningandwriting.Butyouneedtoarrangewithatleasttwofellowclassmatesthatyouwillalltakenotes andsharenoteswitheachotherifabsent.Inadditiontocoursematerials,otheradministrativemattersare discussedinclasssuchastheannouncementofexamdatechange. Ifyouaretakingadistanceeducationcourse,youneedtoregularlyenterthelearningmanagementsystem suchasBlackboardVistaandreviewtheannouncements,discussionlistpostingsandreadandanswer ifappropriateemail.Mostdistanceeducationprofessorsassumethatanythinghehascommunicatedvia thesetoolswillhavebeenreadbythestudentwithin3days.Inshortthismeansyouareresponsiblefor havingreadtheitemsandcompletinganyactionrequested.

PAGE 286

278 CHAPTER26.APPENDIX 26.7StudyHabitsthatBuildtheBrain 12 26.7.1Introduction Duringthespringof2008theauthor,KennethLeroyBusbee,didsomeresearchwithstudentstakingacomputerprogrammingfundamentalscoursetodetermineifusing3x5cardswouldimprovestudentperformance onexams.Inshort,itdid!Thiswasnotasurprise,butitbecameobviousthatmostofusfacultyatall levelsofeducationaswellasstudentshavelittleunderstandingofhowarebrainbuildsunderstandingand longtermmemory. AttachedareseveralPowerPointpresentationsthathavebeensaveinanAdobePDFformat.Please spendafewminutesreviewingtheinformationprovided.Hopefullyitwillhelpstudentstobetterlearnthe subjectstheyarestudying. 26.7.2MainPresentation Linkto:StudyHabitsthatBuildtheBrain 13 26.7.3SpecicTopics Linkto:ReadingtheTextbook 14 Linkto:TakingLectureNotes 15 Linkto:Using3x5Cards 16 Linkto:UsingtheFlashCardActivity 17 12 Thiscontentisavailableonlineat. 13 Seetheleat 14 Seetheleat 15 Seetheleat 16 Seetheleat 17 Seetheleat

PAGE 287

GLOSSARY 279 Glossary A abs Afunctionwithinthecmathstandard libraryinC++whichstandsforabsolute. actionitem Anattributeofiterationcontrol structures. addressoperator Theampersandor&. applications Aninformationsystemorcollectionof programsthathandlesamajortask. array Asequencedcollectionofelementsofthe samedatatypewithasingleidentier name. arrayfunction Auserdenedspecictaskfunction designedtoprocessanarray. arraymember Anelementorvalueinanarray. ASCII AmericanStandardCodeforInformation Interchange assignment Anoperatorthatchangesthevalueofa modiabledataobject. associativity Determinestheorderinwhichthe operatorsofthesameprecedenceare allowedtomanipulatetheoperands. atleastonce Indicatingthattestafterloopsexecutethe actionatleastonce. B banners Asetofcommentlinesusedtohelp separatethefunctionsandothersections ofaprogram. block Anothernameforacompoundstatement. Boolean Adatatyperepresentingtheconceptsof trueandfalse. braces UsedtoidentifyablockofcodeinC++. branching Acontrolstructurethatallowstheowof executiontojumptoadierentpartof theprogram. branchingcontrolstructures Allowtheowofexecutiontojumptoa dierentpartoftheprogram. break Abranchingcontrolstructurethat terminatestheexistingstructure. bubblesort Amethodofswappingarraymembers untiltheyareinthedesiredsequence. C case Acontrolstructurethatdoesmulitway selection. centralprocessingunit Theelectroniccircuitrythatactually executescomputerinstructions. character Adatatyperepresentingsingletext characterslikethealphabet,numeral digits,punctuation,etc. circularnature Connectingthenegativeandpositiveends ofthedomainofanintegerfamilydata type. classmember Anoperatorusedtoinvokefunctions associatedwithaclass.

PAGE 288

280 GLOSSARY close Yourprogramrequestingtheoperating systemtoreleasealethatwas previouslyopened. codechecking Usingtestdatatocheckthecoded programinaspeciclanguagelike C++. comments Informationinsertedintoasourcecodele fordocumentationoftheprogram. commonarea Anareaoftheprogramwherevariables andconstantsaredenedsothatthey areavailabletoallfunctions. compiler Convertssourcecodetoobjectcode. compilerdirective Aninstructiontothecompilertocomplete ataskbeforeformallystartingtocompile theprogram. complexlogic Oftensolvedwithnestedcontrol structures. compoundstatement Aunitofcodeconsistingofzeroormore statements. concatenation Combiningtwostringsintoonestring. conditional AtrinaryC++operatorthatactslikean ifthenelsecontrolstructure. conditionalcompilation Acompilerdirectivethatincludesor excludeslinesofcodebasedonaBoolean expression. condence ThereliancethatStandardLibrary functionsworkproperly. consistent Arulethatsaystotypeidentiernames inupperandlowercaseconsistently throughoutyoursourcecode. constant Adataitemwhosevaluecannotchange duringtheprogram'sexecution. continue Abranchingcontrolstructurethatcauses alooptostopitscurrentiterationand beginthenextone. controlstructures Mechanismsthatallowustocontrolthe owofexecutionwithinaprogram. countingcontrolled Usingavariabletocountupordownto controlaloop. D dataarea Apartofanobjectcodeleusedfor storageofdata. datatype Denesasetofvaluesandasetof operationsthatcanbeappliedonthose values. datetypefamilies 1Nothing2Integer3Floating-Point4 Complex debugging Theprocessofremovingerrorsfroma program.1compiler2linker3logic decisionsymbol Adiamondusedinowchartingforasking aquestionandmakingadecision. decrement Subtractingonefromthevalueofa variable. demotion Goingfromalargerdomaintoasmaller domain. dereferencing Theconceptofusingtheitemtowhicha pointeroraddressispointingat. device Apieceofequipmentthatiselectronically connectedtothememorysothatdata canbetransferredbetweenthememory andthedevice. devicetoken

PAGE 289

GLOSSARY 281 Akeyvalueprovidedbytheoperating systemtoassociateadevicetoyour program. dimension Anaxisofanarray. dowhile Atestafteriterationcontrolstructure availableinC++. documentation Amethodofpreservinginformationuseful toothersinunderstandingan informationsystemorpartthereof. domain Thesetofallowedvaluesforadatatype. double Themostoftenusedoating-pointfamily datatypeusedinC++. dynamicmemory Akastackcreatedmemoryassociatedwith localscope. E escapecode Ancodedirectinganoutputdevicetodo something. evaluation Theprocessofapplyingtheoperatorsto theoperandsandresultinginasingle value. eventcontrolled Usinguserinputtocontrolaloop. exit Apre-denedfunctionusedto prematurelystopaprogramandjumpto theoperatingsystem. explicit Changingavalue'sdatatypewiththecast operator. expression Avalidsequenceofoperandsand operatorsthatreducesorevaluatesto asinglevalue. extraction Akareadingorgettingdatafromaninput device. F factorial Amathproblemthatoftenissolvedusing recursion. lename Thenameanditsextension. lespec Thelocationofalealongwithits lename. ag Avariableorconstantusedtostore informationthatwillnormallybeusedto controltheprogram. exiblecoding Usingthesizeofoperatortocalculatethe numberofmembersinanarray. oatingpoint Adatatyperepresentingnumberswith fractionalparts. owlines Linessometimeswitharrowsthat connectthevariousowchartingsymbols. owcharting Aprogrammingdesigntoolthatuses graphicalelementstovisuallydepictthe owoflogicwithinafunction. folder Anamedareaforstorageofdocumentsor otherlesonadiskdriveorashdrive. for Atestbeforeiterationcontrolstructure typicallyusedforcounting. formatting Modifyingthewaytheoutputis displayed. functioncall Afunction'susingorinvokingofanother function. functiondenition Thecodethatdeneswhatafunction does. functionprototype Afunction'scommunicationsdeclaration toacomplier.

PAGE 290

282 GLOSSARY function Whatmodulesarecalledinthetwo predominantprogramminglanguagesof today:C++andJava. G globalscope Datastoragedenedoutsideofafunction. goto Abranchingcontrolstructurethatcauses thelogictojumptoadierentplacein theprogram. H headerle Alethatcontainsitemswewanttohave includedtowardthetopofoursource code. hierarchychart Conveytherelationshiporbigpictureof thevariousfunctionsinaprogram. highperformancecomputing Groupingmultiplecomputersormultiple computerprocessorstoaccomplishatask inlesstime. I identiername Thenamegivenbytheprogrammerto identifyafunctionorotherprogram itemssuchasvariables. ifthenelse Atwowayselectioncontrolstructure. implementation ThephaseofaSystemsDevelopmentLife Cyclewheretheprogrammerswouldbe assignedtowritespecicprograms. implicit Avaluethathasitsdatatypechanged automatically. include Acompilerdirectivetoinsertthecontents ofaleintotheprogram. increment Addingonetothevalueofavariable. indention Amethodusedtomakesectionsofsource codemorevisible. index Anoperatorthatallowsustoreferencea memberofanarray. indirectionoperator Theasteriskusedfordereferencinga pointer. inniteloop Nomethodofexit,thusabadthing. initializeitem Anattributeofiterationcontrol structures. input/outputsymbol Aparallelogramusedinowchartingfor input/outputinteractions. insertion Akawritingorsendingdatatoanoutput device. integer Adatatyperepresentingwholenumbers. integerdivision Divisionwithnofractionalparts. IPO Inputs-Processing-Outputs iteration Acontrolstructurethatallowssomelines ofcodetobeexecutedmanytimes. L lifecycle SystemsDevelopmentLifeCycle: Planning-Analysis-DesignImplementation-Maintenance linearsearch Usingalooptosequentiallystepthrough anarray. linker Connectsorlinksobjectlesintoan executablele. list Asingledimensionarray. loader Partoftheoperatingsystemthatloads executablelesintomemoryanddirect theCPUtostartrunningtheprogram.

PAGE 291

GLOSSARY 283 localscope Datastoragedenedinsideofafunction. logicaloperator Anoperatorusedtocreatecomplex Booleanexpressions. loopattributes Itemsassociatedwithiterationorlooping controlstructures. loopcontrol Makingsuretheattributesofaloopare properlyhandled. Lvalue Therequirementthattheoperandonthe leftsideoftheassignmentoperatoris modiable,usuallyavariable. M machinedependent Anattributeofaprogramminglanguage thatchangesdependingonthe computer'sCPU. mantissaexponent Thetwointegerpartsofaoating-point value. maximum Akamaxorthelargestmemberofan array. meaningful Arulethatsaysidentiernamesmustbe easilyunderstoodbyanotherreadingthe sourcecode. mightnothappen Indicatingthattestbeforeloopsmightnot executetheaction. minimum Akaminorthesmallestmemberofan array. minus Akaunarynegative. modelchecking Usingtestdatatocheckthedesignmodel usuallydoneinpseudocode. modulararithmetic Asystemofarithmeticforintegerswhere numbers"wraparound". modularization Theabilitytogroupsomelinesofcode intoaunitthatcanbeincludedinour program. modulus Theremainderpartofintegerdivision. multiwayselection Usingcontrolstructurestobeableto selectfrommorethantwochoices. mutuallyexclusive Itemsthatdonotoverlap.Example:true andfalse. N nestedcontrolstructures Placingonecontrolstructureinsideof another. O objectoriented Aprogrammingapproachthat encapsulatesdatawithfunctions. oset Themethodofreferencingarraymembers bystartingatzero. opensource Groupdevelopmentofsourcecodefor softwarethatismadeavailabletothe publicatnocost. open Yourprogramrequestingtheoperating systemtoletithaveaccesstoanexisting leortoopenanewle. operand Avaluethatreceivestheoperator'saction. operator Alanguage-specicsyntacticaltoken usuallyasymbolthatcausesanaction tobetakenononeormoreoperands. P parallelprocessing Dividingataskintopartsthatcanutilize morethanoneprocessor. parallelprogramming

PAGE 292

284 GLOSSARY Involvesdevelopingprogramsthatutilize parallelprocessingalgorithmsthattake advantageofmultipleprocessors. parameterpassing Howthedataiscommunicatedintoand outofafunction. parentheses Changetheorderofevaluationinan expression.Youdowhat'sinthe parenthesesrst. phraseword Wordsusedtomakepseudocodelogic cleartoanyreader. plus Akaunarypositive. pointer Avariablethatholdsanaddressasits value. portability Theabilitytotransportsoftwareonaash driveandthususeitonvariousmachines. postx Placingtheincrementordecrement operatortotherightoftheoperand. pre-processor Therststepthecomplierdoesin convertingsourcecodetoobjectcode. precedence Determinestheorderinwhichthe operatorsareallowedtomanipulatethe operands. precision Theeectonthedomainofoating-point valuesgivenalargerorsmallerstorage areainbytes. prex Placingtheincrementordecrement operatortotheleftoftheoperand. proceduralprogramming Akamodularstructuredprogramming. processsymbol Arectangleusedinowchartingfor normalprocessessuchasassignment. programcontrol Functionsusedtosimplysubdivideand controltheprogram. promotion Goingfromasmallerdomaintoalarger domain. pseudo Meansfalseandincludestheconceptsof fakeorimitation. pseudocode English-likestatementsusedtoconveythe stepsofanalgorithmorfunction. R read Movingdatafromadevicethathasbeen openedintoamemorylocationdenedin yourprogram. recursion Arepetitiveprocessinwhichafunction callsitself. referencevariable Usedwithparameterpassingbyreference. relationaloperator AnoperatorthatgivesaBooleanvalueby evaluatingtherelationshipbetweentwo operands. repeatuntil Atestafteriterationcontrolstructure thatisnotavailableinC++. reservedword Wordsthatcannotbeusedbythe programmerasidentiernamesbecause theyalreadyhaveaspecicmeaning withintheprogramminglanguage. return Abranchingcontrolstructurethatcauses afunctiontojumpbacktothefunction thatcalledit. Rvalue Pullsorfetchesthevaluestoredina variableorconstant. S scope

PAGE 293

GLOSSARY 285 Theareaofasourcecodelewherean identiernameisrecognized. selection Acontrolstructurewhereyouselect betweentwoormorechoices. sequence Acontrolstructurewhereyoudothe itemsinthesequencelisted. sequence Anoperatorusedtoseparatemultiple occurrencesofanitem. sequentialprocessing Usingonlyoneprocessorandcompleting thetasksinasequentialorder. singlequotemarks Usedtocreatecharactertypedatawithin theC++programminglanguage. sizeof Anoperatorthattellsyouhowmany bytesadatatypeoccupiesinstorage. sorting Arrangingdataaccordingtotheirvalues. sourcecode Anycollectionofstatementsor declarationswritteninsome human-readablecomputerprogramming language. specictask Functionsdesignedtobeusedwithseveral programs. stack Apartofthecomputer'smemoryusedfor storageofdata. standardinput Thekeyboard. StandardLibrary Asetofspecictaskfunctionsthathave beenaddedtotheprogramminglanguage foruniversaluse. standardoutput Themonitor. staticmemory Akadataareamemoryassociatedwith globalscope. string Aseriesorarrayofcharactersasasingle pieceofdata. stringclass Acomplexdataitemthatusesobject orientedprogramming. structurechart Anothernameforahierarchychart. structuredprogramming Amethodofplanningprogramsthat avoidsthebranchingcategoryofcontrol structures. sum Latinforsummaoratotal. switch AC++controlstructurethatcanbe madetoactlikeacasecontrolstructure. systemanalyst Computerprofessionalinchargeof creatingapplications. T table Atwodimensionarray. testdata Providinginputvaluesandpredictingthe outputs. testexpression Anexpressionusedtocontrol programmingstructures. testitem Anattributeofiterationcontrol structures. testingshell Aprogramusedtocreatespecictask functions. texteditor Asoftwareprogramforcreatingand editingASCIItextles. textle Aleconsistingofcharactersfromthe ASCIIcharactercodeset. truncation

PAGE 294

286 GLOSSARY Thefractionalpartofaoating-pointdata typethatisdroppedwhenconvertedto aninteger. truthtables Acommonwaytoshowlogical relationships. typedef Allowstheprogrammertocreateanalias, orsynonym,foranexistingdatatype. U udst UserDenedSpecicTask unarynegative Anoperatorthatcausesnegation. unarypositive Aworthlessoperatoralmostneverused. updateitem Anattributeofiterationcontrol structures. userdenedlibrary Alecontainingspecictaskfunctions createdbyindividualstobeusedinmany programs. V variable Adataitemwhosevaluecanchange duringtheprogram'sexecution. versatile Easilymodifyingcodetohandleanother datatype. verticalalignment Amethodoflistingitemsverticallyso thattheyareeasiertoreadquickly. voiddatatype Adatatypethathasnovaluesor operatorsandisusedtorepresent nothing. W warning Acompileralertthattheremightbea problem. while Atestbeforeiterationcontrolstructure availableinC++. wrapping Whenoutputisnotverticallyspaced properly. write Movingdatafromamemorylocation denedinyourprogramtoadevicethat hasbeenopened.

PAGE 295

INDEX 287 IndexofKeywordsandTerms Keywords arelistedbythesectionwiththatkeywordpagenumbersareinparentheses.Keywords donotnecessarilyappearinthetextofthepage.Theyaremerelyassociatedwiththatsection. Ex. apples,1.1 Terms arereferencedbythepagetheyappearon. Ex. apples,1 3 3x5cards,26.7 A abs,98 academicdishonesty,26.5 actionitem,164 addressoperator,239,241 ampersand,239,241 applications,12 arithmeticassignment,50 arithmeticoperators,3.6 array,200,213,247 arraydatatype,18.1 arrayfunction,224 arrayindexoperator,18.2 arraymember,215,248 arraymembers,18.3 ASCII,104,199 ASCIICharacterSet,26.3 assignment,39,167 associativity,37,26.1 asterisk,241,242 atleastonce,164 B banners,81 bitsasags,13.2 blackscreenoutputbox,67 block,138 BloodshedDev-C++5compiler/IDE,13,21, 29,42,43,51,54,55,64,70,76,83,91,92,94, 98,99,104,107,130,136,139,148,156,169, 181,189,190,194,195,200,203,209,210, 217,218,222,224,225,226,227,229,231, 233,235,237,241,243,244,247,249,250,261 Boolean,135 Booleanexpression,52,133,135,136,146, 161,167,168,175 braces,20,82,137 branching,113 branchingcontrolstructures,152 break,152 bubblesort,232 C C++datatypes,3.1 C++programlayout,1.3 C: n Dev-Cpp n ,15,15,15 call,76 capacitytoconcentrate,26.6 case,152 centralprocessingunit,260 character,104 cin,67 circularnature,189 classmember,200 close,223 closedcommunicationsmodel,240,242 codechecking,29 collusion,26.5 comments,81 commonarea,77 compiler,65 compilerdirective,69 compiler/IDE,1.2 complexlogic,195 compoundstatement,138 computationalscience,24.2 concatenation,200 conditional,208 conditionalcompilation,249 conditionalexpression,17.1 conditionaloperator,17.1 condence,98 consistent,82 constant,37 continue,152 controlstructures,112,11.1 countingcontrolled,180 countingloops,112 cout,67 D dataarea,90 datatype,34 datatypeconversion,3.7 datetypefamilies,34 debugging,65

PAGE 296

288 INDEX decisionsymbol,129 decrement,175 denedconstant,36 denition,76 demotion,42 dereferencing,243 devcpp-4.9.9.2_setup.exe,15,15 device,67 devicetoken,223 dimension,214,248 distributedprocessing,24.2 dowhile,164 documentation,81 domain,34 double,49 DriveLetter,15 DriveLetter: n Dev-Cpp n ,15 dynamicmemory,225 dynamicmemoryallocation,224 E equality,167 escapecode,68 evaluation,38 eventcontrolled,180 exit,152 explicit,42 expression,37 extraction,68 F factorial,209 FileExtensions,26.4 lename,223 lespec,223 xed,15.3 ag,166 ashcards,26.7 exiblecoding,217,236 oat,4.2 oatingpoint,34 oating-pointdatatype,4.2 oating-pointdivision,53 owlines,129 owcharting,10.3,129 folder,14 for,186 formatting,190 function,19 functioncall,20 functiondenition,20 functionprototype,20 G globalscope,90,224,239 goto,152 H headerle,93 hierarchychart,75 highperformancecomputing,260 HIPO,27 I IDE,1.2 identiername,20 identiernames,3.2 ifthenelse,111,134,137 implementation,13 implicit,42 include,69 increment,175 indention,82 index,215,248 indirectionoperator,241,243 inniteloop,164,14.2,15.1 initializeitem,180 Input-OutputStream,67,68 input/outputsymbol,129 insertion,68 integer,34 integerdatatype,4.1 integerdivision,53 IntegratedDevelopmentEnvironment,59 IPO,26,27 iteration,113 iterationasalttorecursion,17.2 K keywords,26.2 L lecturenotes,26.7 lifecycle,12 linearsearch,230 linker,65 list,214,248 literalconstant,36 loader,65 localscope,90,224,239,240,242 logicaloperator,148 longdouble,4.2 loopattributes,179 loopcontrol,189 Lvalue,52 M machinedependent,48,104 mantissaexponent,49 maximum,230 meaningful,82 memoryconstant,37 mightnothappen,180

PAGE 297

INDEX 289 minimum,230 minus,16.2,202 modelchecking,29 modulararithmetic,189 modularstructuredprogramming,253 modularization,19,7.1 modulo,15.2 modulus,54 multidimensionalarrays,23.1 multiplicationtable,15.4 multiwayselection,112,146 mutuallyexclusive,134 N negation,16.2 nestedcontrolstructures,146,15.4 nestedifthenelse,151 nocommunicationinwithno communicationout,76 O objectoriented,254 oset,215,248 open,223 opensource,13 operand,37 operator,37,269 P parallelprocessing,260 parallelprogramming,260 parameterpassing,20,76,90 parentheses,38 phraseword,74,113 plus,16.2,202 pointer,240,241,242 portability,13 postx,175 pre-processor,65 precedence,37 precedencechart,26.1 precision,49,15.3 prex,175 proceduralprogramming,254 processsymbol,129 procrastination,26.6 programcontrol,20,6.3,90 programdesign,2.1 programdocumentation,6.5 promotion,42 prototype,76 prototypesle,91 pseudo,27 pseudocode,26,2.2 pseudocodeforcontrolstructures,10.2 pseudocodeforfunctions,6.1 R read,223 recursion,209 referencevariable,241,242 regularstudytimes,26.6 relationaloperator,136 repeatuntil,168 repetitivealgorithms,17.2 reservedword,36 reservedwords,26.2 return,152 Rvalue,52 S scholasticdishonesty,26.5 scope,91 selection,113 sequence,107,112 sequentialprocessing,260 setw,15.3 showpoint,15.3 singlequotemarks,104 sizeof,105,216 sorting,232 sourcecode,14,6.5,221 specictask,20,90 specictaskfunctions,7.1 stack,91 standardfunctions,97 standardinput,68 StandardLibrary,98 standardoutput,68 staticmemory,225 staticmemoryallocation,224 string,50,199,213 stringclass,200 structurechart,75 structuredprogramming,113 sum,226 supercomputing,24.2 switch,152 systemanalyst,12 SystemsDevelopmentLifeCycle,11 T table,214,248 testafterloop,162 testafterloops,112 testbeforeloop,176,184 testbeforeloops,112 testdata,26,2.3 testexpression,52,133,135,136,146,161, 166,168,175,183

PAGE 298

290 INDEX testitem,164 testingshell,93 texteditor,65 textle,223 timecommitment,26.6 truncation,42 truthtables,148 twowayselection,11.1 two-wayselection,112 typedef,106,236 U udst,93 unarynegative,16.2,202 unarypositive,16.2,202 underscore,221 updateitem,164 userdenedheaderle,7.3 userdenedlibrary,90 userdenedspecictask,223,225 userlibrary,7.3 V variable,37 variableasaag,13.2 varietyandrepetition,26.6 verifyheaderprogram,91 versatile,236 verticalalignment,81 verticalspacing,189 voiddatatype,78 W warning,65 while,111,179 wrapping,190 write,223

PAGE 299

ATTRIBUTIONS 291 Attributions Collection: ProgrammingFundamentals-AModularStructuredApproachusingC++ Editedby:KennethLeroyBusbee URL:http://cnx.org/content/col10621/1.17/ License:http://creativecommons.org/licenses/by/2.0/ Module:"Preface-FundamentalsIusingC++" Usedhereas:"Preface" By:KennethLeroyBusbee URL:http://cnx.org/content/m19049/1.14/ Pages:1-3 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"AuthorAcknowledgements-FundamentalsIusingC++" Usedhereas:"AuthorAcknowledgements" By:KennethLeroyBusbee URL:http://cnx.org/content/m19055/1.4/ Page:5 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"OrientationandSyllabus-FundamentalsIusingC++" Usedhereas:"OrientationandSyllabus" By:KennethLeroyBusbee URL:http://cnx.org/content/m19684/1.8/ Pages:7-9 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"SystemsDevelopmentLifeCycle" By:KennethLeroyBusbee URL:http://cnx.org/content/m18684/1.5/ Pages:11-13 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"BloodshedDev-C++5Compiler/IDE" By:KennethLeroyBusbee URL:http://cnx.org/content/m18785/1.14/ Pages:13-16 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"ModularizationandC++ProgramLayout" By:KennethLeroyBusbee URL:http://cnx.org/content/m18861/1.11/ Pages:16-20 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/

PAGE 300

292 ATTRIBUTIONS Module:"Practice1:IntroductiontoProgramming" By:KennethLeroyBusbee URL:http://cnx.org/content/m22450/1.2/ Pages:20-22 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ProgramDesign" By:KennethLeroyBusbee URL:http://cnx.org/content/m18686/1.4/ Pages:25-26 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Pseudocode" By:KennethLeroyBusbee URL:http://cnx.org/content/m18648/1.9/ Pages:26-27 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"TestData" By:KennethLeroyBusbee URL:http://cnx.org/content/m18781/1.3/ Pages:27-29 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Practice2:ProgramPlanning&Design" By:KennethLeroyBusbee URL:http://cnx.org/content/m22453/1.2/ Pages:29-31 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"DataTypesinC++" By:KennethLeroyBusbee URL:http://cnx.org/content/m18653/1.11/ Pages:33-34 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"IdentierNames" By:KennethLeroyBusbee URL:http://cnx.org/content/m18692/1.4/ Pages:35-36 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"ConstantsandVariables" By:KennethLeroyBusbee URL:http://cnx.org/content/m18719/1.7/ Pages:36-37 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/

PAGE 301

ATTRIBUTIONS 293 Module:"DataManipulation" By:KennethLeroyBusbee URL:http://cnx.org/content/m18705/1.5/ Pages:37-38 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"AssignmentOperator" By:KennethLeroyBusbee URL:http://cnx.org/content/m18725/1.2/ Pages:38-39 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"ArithmeticOperators" By:KennethLeroyBusbee URL:http://cnx.org/content/m18706/1.3/ Pages:39-40 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"DataTypeConversions" By:KennethLeroyBusbee URL:http://cnx.org/content/m18744/1.6/ Pages:40-42 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Practice3:Data&Operators" By:KennethLeroyBusbee URL:http://cnx.org/content/m22455/1.1/ Pages:42-44 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"IntegerDataType" By:KennethLeroyBusbee URL:http://cnx.org/content/m18654/1.5/ Pages:47-48 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Floating-PointDataType" By:KennethLeroyBusbee URL:http://cnx.org/content/m18657/1.5/ Pages:48-49 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"StringDataType" By:KennethLeroyBusbee URL:http://cnx.org/content/m18656/1.5/ Pages:49-50 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/

PAGE 302

294 ATTRIBUTIONS Module:"ArithmeticAssignmentOperators" By:KennethLeroyBusbee URL:http://cnx.org/content/m18743/1.6/ Pages:50-51 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"LvalueandRvalue" By:KennethLeroyBusbee URL:http://cnx.org/content/m18058/1.11/ Pages:51-52 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"IntegerDivisionandModulus" By:KennethLeroyBusbee URL:http://cnx.org/content/m18717/1.12/ Pages:53-55 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Practice4:OftenUsedDataTypes" By:KennethLeroyBusbee URL:http://cnx.org/content/m22456/1.1/ Pages:55-56 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"IntegratedDevelopmentEnvironment" By:KennethLeroyBusbee URL:http://cnx.org/content/m18920/1.8/ Pages:59-65 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"StandardInputandOutput" By:KennethLeroyBusbee URL:http://cnx.org/content/m18835/1.3/ Pages:65-68 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"CompilerDirectives" By:KennethLeroyBusbee URL:http://cnx.org/content/m18787/1.6/ Pages:68-69 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Practice5:IntegratedDevelopmentEnvironment" By:KennethLeroyBusbee URL:http://cnx.org/content/m22457/1.1/ Pages:69-71 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 303

ATTRIBUTIONS 295 Module:"PseudocodeExamplesforFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m19136/1.6/ Pages:73-74 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"HierarchyorStructureChart" By:KennethLeroyBusbee URL:http://cnx.org/content/m18682/1.3/ Pages:74-75 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"ProgramControlFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m19145/1.8/ Pages:75-77 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"VoidDataType" By:KennethLeroyBusbee URL:http://cnx.org/content/m18655/1.3/ Pages:77-78 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"DocumentationandMakingSourceCodeReadable" By:KennethLeroyBusbee URL:http://cnx.org/content/m18912/1.3/ Pages:78-82 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Practice6:ProgramControlFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m22458/1.2/ Pages:82-86 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"SpecicTaskFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m19146/1.3/ Pages:89-90 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"GlobalvsLocalDataStorage" By:KennethLeroyBusbee URL:http://cnx.org/content/m19147/1.4/ Pages:90-91 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/

PAGE 304

296 ATTRIBUTIONS Module:"UsingaHeaderFileforUserDenedSpecicTaskFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m19346/1.4/ Pages:91-93 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Practice7:SpecicTaskFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m22459/1.1/ Pages:93-94 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"StandardLibraries" By:KennethLeroyBusbee URL:http://cnx.org/content/m19202/1.4/ Pages:97-98 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Practice8:StandardLibraries" By:KennethLeroyBusbee URL:http://cnx.org/content/m22460/1.2/ Pages:99-100 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"CharacterDataType" By:KennethLeroyBusbee URL:http://cnx.org/content/m18669/1.5/ Pages:103-104 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"SizeofOperator" By:KennethLeroyBusbee URL:http://cnx.org/content/m18736/1.7/ Pages:104-105 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Typedef-AnAlias" By:KennethLeroyBusbee URL:http://cnx.org/content/m18741/1.4/ Pages:105-106 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"SequenceOperator" By:KennethLeroyBusbee URL:http://cnx.org/content/m18690/1.7/ Pages:106-107 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/

PAGE 305

ATTRIBUTIONS 297 Module:"Practice9:CharacterData,Sizeof,Typedef,Sequence" By:KennethLeroyBusbee URL:http://cnx.org/content/m22461/1.2/ Pages:107-108 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"StructuredProgramming" By:KennethLeroyBusbee URL:http://cnx.org/content/m19628/1.6/ Pages:111-113 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"PseudocodeExamplesforControlStructures" By:KennethLeroyBusbee URL:http://cnx.org/content/m18649/1.12/ Pages:113-114 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"Flowcharting" By:KennethLeroyBusbee URL:http://cnx.org/content/m19623/1.5/ Pages:115-129 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice10:IntroductiontoStructuredProgramming" By:KennethLeroyBusbee URL:http://cnx.org/content/m19692/1.13/ Pages:129-130 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"IfThenElse" By:KennethLeroyBusbee URL:http://cnx.org/content/m19679/1.3/ Pages:133-134 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"BooleanDataType" By:KennethLeroyBusbee URL:http://cnx.org/content/m19544/1.4/ Page:135 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"RelationalOperators" By:KennethLeroyBusbee URL:http://cnx.org/content/m19549/1.10/ Pages:136-137 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/

PAGE 306

298 ATTRIBUTIONS Module:"CompoundStatement" By:KennethLeroyBusbee URL:http://cnx.org/content/m19683/1.2/ Pages:137-138 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice11:TwoWaySelection" By:KennethLeroyBusbee URL:http://cnx.org/content/m19764/1.14/ Pages:138-140 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"NestedIfThenElse" By:KennethLeroyBusbee URL:http://cnx.org/content/m19951/1.5/ Pages:143-146 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"LogicalOperators" By:KennethLeroyBusbee URL:http://cnx.org/content/m19847/1.6/ Pages:146-148 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"CaseControlStructure" By:KennethLeroyBusbee URL:http://cnx.org/content/m19963/1.2/ Pages:148-152 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"BranchingControlStructures" By:KennethLeroyBusbee URL:http://cnx.org/content/m19947/1.2/ Pages:152-155 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice12:MultiwaySelection" By:KennethLeroyBusbee URL:http://cnx.org/content/m19968/1.10/ Pages:155-158 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"DoWhileLoop" By:KennethLeroyBusbee URL:http://cnx.org/content/m20596/1.4/ Pages:161-164 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 307

ATTRIBUTIONS 299 Module:"FlagConcept" By:KennethLeroyBusbee URL:http://cnx.org/content/m20404/1.5/ Pages:164-166 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"AssignmentvsEqualitywithinC++" By:KennethLeroyBusbee URL:http://cnx.org/content/m19542/1.6/ Pages:166-167 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"RepeatUntilLoop" By:KennethLeroyBusbee URL:http://cnx.org/content/m20597/1.2/ Pages:167-168 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice13:TestAfterLoops" By:KennethLeroyBusbee URL:http://cnx.org/content/m20642/1.7/ Pages:168-170 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"IncrementandDecrementOperators" By:KennethLeroyBusbee URL:http://cnx.org/content/m20499/1.3/ Pages:173-175 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"WhileLoop" By:KennethLeroyBusbee URL:http://cnx.org/content/m20598/1.6/ Pages:175-180 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice14:TestBeforeLoops" By:KennethLeroyBusbee URL:http://cnx.org/content/m20643/1.9/ Pages:180-181 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ForLoop" By:KennethLeroyBusbee URL:http://cnx.org/content/m20600/1.2/ Pages:183-186 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 308

300 ATTRIBUTIONS Module:"CircularNatureoftheIntegerDataTypeFamily" By:KennethLeroyBusbee URL:http://cnx.org/content/m20743/1.3/ Pages:187-189 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"FormattingOutput" By:KennethLeroyBusbee URL:http://cnx.org/content/m20660/1.3/ Pages:189-190 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"NestedForLoops" By:KennethLeroyBusbee URL:http://cnx.org/content/m20653/1.5/ Pages:191-195 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice15:CountingLoops" By:KennethLeroyBusbee URL:http://cnx.org/content/m20809/1.5/ Pages:195-196 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"StringClasswithinC++" By:KennethLeroyBusbee URL:http://cnx.org/content/m20796/1.5/ Pages:199-200 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"UnaryPositiveandNegativeOperators" By:KennethLeroyBusbee URL:http://cnx.org/content/m20501/1.1/ Pages:201-202 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice16:StringClass,UnaryPostitiveandNegative" By:KennethLeroyBusbee URL:http://cnx.org/content/m20810/1.4/ Pages:202-204 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ConditionalOperator" By:KennethLeroyBusbee URL:http://cnx.org/content/m20811/1.6/ Pages:207-208 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 309

ATTRIBUTIONS 301 Module:"RecursionvsIteration" By:KennethLeroyBusbee URL:http://cnx.org/content/m20814/1.2/ Pages:208-209 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice17:ConditionalOperatorandRecursion" By:KennethLeroyBusbee URL:http://cnx.org/content/m20815/1.5/ Pages:209-211 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ArrayDataType" By:KennethLeroyBusbee URL:http://cnx.org/content/m21315/1.2/ Pages:213-214 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ArrayIndexOperator" By:KennethLeroyBusbee URL:http://cnx.org/content/m21316/1.2/ Pages:214-215 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"DisplayingArrayMembers" By:KennethLeroyBusbee URL:http://cnx.org/content/m21317/1.4/ Pages:215-217 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice18:IntroductiontoArrays" By:KennethLeroyBusbee URL:http://cnx.org/content/m21321/1.4/ Pages:217-218 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"FileInputandOutput" By:KennethLeroyBusbee URL:http://cnx.org/content/m21623/1.2/ Pages:221-223 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ArraysandFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m21624/1.1/ Pages:223-224 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 310

302 ATTRIBUTIONS Module:"LoadinganArrayfromaFile" By:KennethLeroyBusbee URL:http://cnx.org/content/m21625/1.1/ Pages:224-225 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"MathStatisticswithArrays" By:KennethLeroyBusbee URL:http://cnx.org/content/m21626/1.1/ Pages:225-226 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice19:FileI/OandArrayFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m21630/1.3/ Pages:226-227 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"FindingaSpecicMemberofanArray" By:KennethLeroyBusbee URL:http://cnx.org/content/m21627/1.1/ Pages:229-230 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"SortinganArray" By:KennethLeroyBusbee URL:http://cnx.org/content/m21628/1.1/ Pages:230-232 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice20:MoreArrayFunctions" By:KennethLeroyBusbee URL:http://cnx.org/content/m21631/1.3/ Pages:232-233 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"VersatileCodewithTypedef" By:KennethLeroyBusbee URL:http://cnx.org/content/m21629/1.1/ Pages:235-236 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 311

ATTRIBUTIONS 303 Module:"Practice21:MoreonTypedef" By:KennethLeroyBusbee URL:http://cnx.org/content/m21632/1.3/ Pages:236-237 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"AddressOperator" By:KennethLeroyBusbee URL:http://cnx.org/content/m22148/1.2/ Pages:239-240 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ParameterPassingbyReference" By:KennethLeroyBusbee URL:http://cnx.org/content/m22150/1.3/ Pages:240-241 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"PointerDataType" By:KennethLeroyBusbee URL:http://cnx.org/content/m22151/1.2/ Page:241 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"IndirectionOperator" By:KennethLeroyBusbee URL:http://cnx.org/content/m22152/1.1/ Pages:242-243 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice22:Pointers" By:KennethLeroyBusbee URL:http://cnx.org/content/m22153/1.3/ Pages:243-245 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"MultidimensionalArrays" By:KennethLeroyBusbee URL:http://cnx.org/content/m22203/1.2/ Pages:247-248 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ConditionalCompilation" By:KennethLeroyBusbee URL:http://cnx.org/content/m22204/1.3/ Pages:248-249 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 312

304 ATTRIBUTIONS Module:"Practice23:MoreArrays&CompilerDirectives" By:KennethLeroyBusbee URL:http://cnx.org/content/m22205/1.2/ Pages:249-250 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"ObjectOrientedProgramming" By:KennethLeroyBusbee URL:http://cnx.org/content/m22188/1.2/ Pages:253-254 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"UnderstandingHighPerformanceComputing" By:KennethLeroyBusbee URL:http://cnx.org/content/m19804/1.6/ Pages:254-260 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Practice24:OOP&HPC" By:KennethLeroyBusbee URL:http://cnx.org/content/m22194/1.4/ Pages:260-262 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Review:FoundationTopicsGroup:1-5" By:KennethLeroyBusbee URL:http://cnx.org/content/m22418/1.2/ Page:265 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Review:ModularProgrammingGroup:6-9" By:KennethLeroyBusbee URL:http://cnx.org/content/m22421/1.2/ Page:266 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Review:StructuredProgrammingGroup:10-16" By:KennethLeroyBusbee URL:http://cnx.org/content/m21653/1.5/ Pages:266-267 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"Review:IntermediateTopicsGroup:17-21" By:KennethLeroyBusbee URL:http://cnx.org/content/m21642/1.4/ Pages:267-268 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 313

ATTRIBUTIONS 305 Module:"Review:AdvancedTopicsGroup:22-24" By:KennethLeroyBusbee URL:http://cnx.org/content/m22215/1.4/ Page:268 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/ Module:"AbbreviatedPrecedenceChartforC++Operators" By:KennethLeroyBusbee URL:http://cnx.org/content/m18168/1.12/ Pages:269-271 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"C++ReservedKeywords" By:KennethLeroyBusbee URL:http://cnx.org/content/m18181/1.5/ Pages:271-272 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"ASCIICharacterSet" By:KennethLeroyBusbee URL:http://cnx.org/content/m18169/1.7/ Pages:272-273 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"ShowHideFileExtensions" By:KennethLeroyBusbee URL:http://cnx.org/content/m18100/1.4/ Page:273 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"AcademicorScholasticDishonesty" By:KennethLeroyBusbee URL:http://cnx.org/content/m18096/1.8/ Pages:273-275 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"SuccessfulLearningSkills" By:KennethLeroyBusbee URL:http://cnx.org/content/m18101/1.9/ Pages:275-277 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/2.0/ Module:"StudyHabitsthatBuildtheBrain" By:KennethLeroyBusbee URL:http://cnx.org/content/m19977/1.4/ Page:278 Copyright:KennethLeroyBusbee License:http://creativecommons.org/licenses/by/3.0/

PAGE 314

ProgrammingFundamentals-AModularStructuredApproachusingC++ ProgrammingFundamentals-AModularStructuredApproachusingC++iswrittenbyKennethLeroy Busbee,afacultymemberatHoustonCommunityCollegeinHouston,Texas.Thematerialsusedinthis textbook/collectionweredevelopedbytheauthorandothersasindependentmodulesforpublicationwithin theConnexionsenvironment.Programmingfundamentalsareoftendividedintothreecollegecourses:Modular/Structured,ObjectOrientedandDataStructures.Thistextbook/collectioncoverstherstofthose threecourses. AboutConnexions Since1999,Connexionshasbeenpioneeringaglobalsystemwhereanyonecancreatecoursematerialsand makethemfullyaccessibleandeasilyreusablefreeofcharge.WeareaWeb-basedauthoring,teachingand learningenvironmentopentoanyoneinterestedineducation,includingstudents,teachers,professorsand lifelonglearners.Weconnectideasandfacilitateeducationalcommunities. Connexions'smodular,interactivecoursesareinuseworldwidebyuniversities,communitycolleges,K-12 schools,distancelearners,andlifelonglearners.Connexionsmaterialsareinmanylanguages,including English,Spanish,Chinese,Japanese,Italian,Vietnamese,French,Portuguese,andThai.Connexionsispart ofanexcitingnewinformationdistributionsystemthatallowsfor PrintonDemandBooks .Connexions haspartneredwithinnovativeon-demandpublisherQOOPtoacceleratethedeliveryofprintedcourse materialsandtextbooksintoclassroomsworldwideatlowerpricesthantraditionalacademicpublishers.