Tải bản đầy đủ - 0 (trang)
Chapter 2. Introduction to C++ Programming

Chapter 2. Introduction to C++ Programming

Tải bản đầy đủ - 0trang

Chapter2.IntroductiontoC++

Programming

What'sinaname?thatwhichwecallaroseByany

othernamewouldsmellassweet.

WilliamShakespeare

Whenfacedwithadecision,Ialwaysask,"What

wouldbethemostfun?"

PeggyWalker

"Takesomemoretea,"theMarchHaresaidtoAlice,

veryearnestly."I'vehadnothingyet,"Alicereplied

inanoffendedtone:"soIcan'ttakemore.""You

meanyoucan'ttakeless,"saidtheHatter:"it'svery

easytotakemorethannothing."

LewisCarroll

Highthoughtsmusthavehighlanguage.

Aristophanes

OBJECTIVES

Inthischapteryouwilllearn:

TowritesimplecomputerprogramsinC++.

Towritesimpleinputandoutputstatements.

Tousefundamentaltypes.



Basiccomputermemoryconcepts.

Tousearithmeticoperators.

Theprecedenceofarithmeticoperators.

Towritesimpledecision-makingstatements.



[Page37]

Outline

2.1Introduction

2.2FirstPrograminC++:PrintingaLineofText

2.3ModifyingOurFirstC++Program

2.4AnotherC++Program:AddingIntegers

2.5MemoryConcepts

2.6Arithmetic

2.7DecisionMaking:EqualityandRelationalOperators

2.8(Optional)SoftwareEngineeringCaseStudy:Examiningthe

ATMRequirementsDocument

2.9Wrap-Up

Summary

Terminology

Self-ReviewExercises



AnswerstoSelf-ReviewExercises

Exercises







[Page37(continued)]



2.1.Introduction

WenowintroduceC++programming,whichfacilitatesa

disciplinedapproachtoprogramdesign.MostoftheC++

programsyouwillstudyinthisbookprocessinformationand

displayresults.Inthischapter,wepresentfiveexamplesthat

demonstratehowyourprogramscandisplaymessagesand

obtaininformationfromtheuserforprocessing.Thefirstthree

examplessimplydisplaymessagesonthescreen.Thenextisa

programthatobtainstwonumbersfromauser,calculatestheir

sumanddisplaystheresult.Theaccompanyingdiscussion

showsyouhowtoperformvariousarithmeticcalculationsand

savetheirresultsforlateruse.Thefifthexampledemonstrates

decision-makingfundamentalsbyshowingyouhowtocompare

twonumbers,thendisplaymessagesbasedonthecomparison

results.Weanalyzeeachprogramonelineatatimetohelpyou

easeyourwayintoC++programming.Tohelpyouapplythe

skillsyoulearnhere,weprovidemanyprogrammingproblems

inthechapter'sexercises.



[Page37(continued)]



2.2.FirstPrograminC++:PrintingaLineofText

C++usesnotationsthatmayappearstrangeto

nonprogrammers.Wenowconsiderasimpleprogramthat

printsalineoftext(Fig.2.1).Thisprogramillustratesseveral

importantfeaturesoftheC++language.Weconsidereachline

indetail.



Figure2.1.Text-printingprogram.

(Thisitemisdisplayedonpage38intheprintversion)



1//Fig.2.1:fig02_01.cpp

2//Text-printingprogram.

3#include//allowsprogramtooutputdatatothescreen

4

5//functionmainbeginsprogramexecution

6intmain()

7{

8std::cout<<"WelcometoC++!\n";//displaymessage

9

10return0;//indicatethatprogramendedsuccessfully

11

12}//endfunctionmain



WelcometoC++!



Lines1and2

//Fig.2.1:fig02_01.cpp

//Text-printingprogram.



eachbeginwith//,indicatingthattheremainderofeachlineis

acomment.Programmersinsertcommentstodocument

programsandalsohelppeoplereadandunderstandthem.

Commentsdonotcausethecomputertoperformanyaction

whentheprogramisruntheyareignoredbytheC++compiler

anddonotcauseanymachine-languageobjectcodetobe

generated.ThecommentText-printingprogramdescribesthe

purposeoftheprogram.Acommentbeginningwith//iscalled

asingle-linecommentbecauseitterminatesattheendofthe

currentline.[Note:C++programmersalsomayuseC'sstylein

whichacommentpossiblycontainingmanylinesbeginswiththe

pairofcharacters/*andendswith*/.]



[Page38]

GoodProgrammingPractice2.1

Everyprogramshouldbeginwithacommentthat

describesthepurposeoftheprogram,author,dateand

time.(Wearenotshowingtheauthor,dateandtimein

thisbook'sprogramsbecausethisinformationwouldbe

redundant.)



Line3



#include//allowsprogramtooutputdatatothescr



isapreprocessordirective,whichisamessagetotheC++

preprocessor(introducedinSection1.14).Linesthatbeginwith



#areprocessedbythepreprocessorbeforetheprogramis

compiled.Thislinenotifiesthepreprocessortoincludeinthe

programthecontentsoftheinput/outputstreamheaderfile

.Thisfilemustbeincludedforanyprogramthat

outputsdatatothescreenorinputsdatafromthekeyboard

usingC++-stylestreaminput/output.TheprograminFig.2.1

outputsdatatothescreen,aswewillsoonsee.Wediscuss

headerfilesinmoredetailinChapter6andexplainthecontents

ofiostreaminChapter15.



CommonProgrammingError2.1

Forgettingtoincludetheheaderfileina

programthatinputsdatafromthekeyboardoroutputs

datatothescreencausesthecompilertoissueanerror

message,becausethecompilercannotrecognize

referencestothestreamcomponents(e.g.,cout).



Line4issimplyablankline.Programmersuseblanklines,

spacecharactersandtabcharacters(i.e.,"tabs")tomake

programseasiertoread.Together,thesecharactersareknown

aswhitespace.White-spacecharactersarenormallyignored

bythecompiler.Inthischapterandseveralthatfollow,we

discussconventionsforusingwhite-spacecharactersto

enhanceprogramreadability.



GoodProgrammingPractice2.2

Useblanklinesandspacecharacterstoenhanceprogram

readability.



[Page39]

Line5

//functionmainbeginsprogramexecution



isanothersingle-linecommentindicatingthatprogram

executionbeginsatthenextline.

Line6

intmain()



isapartofeveryC++program.Theparenthesesaftermain

indicatethatmainisaprogrambuildingblockcalledafunction.

C++programstypicallyconsistofoneormorefunctionsand

classes(asyouwilllearninChapter3).Exactlyonefunctionin

everyprogrammustbemain.Figure2.1containsonlyone

function.C++programsbeginexecutingatfunctionmain,even

ifmainisnotthefirstfunctionintheprogram.Thekeywordint

totheleftofmainindicatesthatmain"returns"aninteger(whole

number)value.Akeywordisawordincodethatisreserved

byC++foraspecificuse.ThecompletelistofC++keywords

canbefoundinFig.4.3.Wewillexplainwhatitmeansfora

functionto"returnavalue"whenwedemonstratehowtocreate

yourownfunctionsinSection3.5andwhenwestudyfunctions

ingreaterdepthinChapter6.Fornow,simplyincludethe

keywordinttotheleftofmainineachofyourprograms.

Theleftbrace,{,(line7)mustbeginthebodyofevery

function.Acorrespondingrightbrace,},(line12)mustend



eachfunction'sbody.Line8

std::cout<<"WelcometoC++!\n";//displaymessage



instructsthecomputertoperformanactionnamely,toprint

thestringofcharacterscontainedbetweenthedouble

quotationmarks.Astringissometimescalledacharacter

string,amessageorastringliteral.Werefertocharacters

betweendoublequotationmarkssimplyasstrings.Whitespacecharactersinstringsarenotignoredbythecompiler.

Theentireline8,includingstd::cout,the<
string"WelcometoC++!\n"andthesemicolon(;),iscalleda

statement.EveryC++statementmustendwithasemicolon

(alsoknownasthestatementterminator).Preprocessor

directives(like#include)donotendwithasemicolon.Output

andinputinC++areaccomplishedwithstreamsofcharacters.

Thus,whentheprecedingstatementisexecuted,itsendsthe

streamofcharactersWelcometoC++!\ntothestandardoutput

streamobjectstd::coutwhichisnormally"connected"tothe

screen.Wediscussstd::cout'smanyfeaturesindetailinChapter

15,StreamInput/Output.

Noticethatweplacedstd::beforecout.Thisisrequiredwhenwe

usenamesthatwe'vebroughtintotheprogrambythe

preprocessordirective#include.Thenotationstd::cout

specifiesthatweareusinganame,inthiscasecout,that

belongsto"namespace"std.Thenamescin(thestandardinput

stream)andcerr(thestandarderrorstream)introducedin

Chapter1alsobelongtonamespacestd.Namespacesarean

advancedC++featurethatwediscussindepthinChapter24,

OtherTopics.Fornow,youshouldsimplyremembertoinclude

std::beforeeachmentionofcout,cinandcerrinaprogram.This

canbecumbersomeinFig.2.13,weintroducetheusing

declaration,whichwillenableustoomitstd::beforeeachuse



ofanameinthestdnamespace.

The<
operator.Whenthisprogramexecutes,thevaluetotheright

oftheoperator,therightoperand,isinsertedintheoutput

stream.Noticethattheoperatorpointsinthedirectionofwhere

thedatagoes.Thecharactersoftherightoperandnormally

printexactlyastheyappearbetweenthedoublequotes.Notice,

however,thatthecharacters\narenotprintedonthescreen.

Thebackslash(\)iscalledanescapecharacter.Itindicates

thata"special"characteristobeoutput.Whenabackslashis

encounteredinastringofcharacters,thenextcharacteris

combinedwiththebackslashtoformanescapesequence.

Theescapesequence\nmeansnewline.Itcausesthecursor

(i.e.,thecurrentscreen-positionindicator)tomovetothe

beginningofthenextlineonthescreen.Someothercommon

escapesequencesarelistedinFig.2.2.



[Page40]

Figure2.2.Escapesequences.

Escape

sequence



Description



\n



Newline.Positionthescreencursortothebeginning

ofthenextline.



\t



Horizontaltab.Movethescreencursortothenext

tabstop.



\r



Carriagereturn.Positionthescreencursortothe

beginningofthecurrentline;donotadvancetothe

nextline.



\a



Alert.Soundthesystembell.



\\



Backslash.Usedtoprintabackslashcharacter.



\'



Singlequote.Usetoprintasinglequotecharacter.



\"



Doublequote.Usedtoprintadoublequote

character.



CommonProgrammingError2.2

OmittingthesemicolonattheendofaC++statementis

asyntaxerror.(Again,preprocessordirectivesdonot

endinasemicolon.)Thesyntaxofaprogramming

languagespecifiestherulesforcreatingaproper

programinthatlanguage.Asyntaxerroroccurswhen

thecompilerencounterscodethatviolatesC++'s

languagerules(i.e.,itssyntax).Thecompilernormally

issuesanerrormessagetohelptheprogrammerlocate

andfixtheincorrectcode.Syntaxerrorsarealsocalled

compilererrors,compile-timeerrorsorcompilation

errors,becausethecompilerdetectsthemduringthe

compilationphase.Youwillbeunabletoexecuteyour

programuntilyoucorrectallthesyntaxerrorsinit.As

youwillsee,somecompilationerrorsarenotsyntax

errors.



Line10

return0;//indicatethatprogramendedsuccessfully



isoneofseveralmeanswewillusetoexitafunction.When

thereturnstatementisusedattheendofmain,asshownhere,

thevalue0indicatesthattheprogramhasterminated

successfully.InChapter6wediscussfunctionsindetail,andthe

reasonsforincludingthisstatementwillbecomeclear.Fornow,



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 2. Introduction to C++ Programming

Tải bản đầy đủ ngay(0 tr)

×