Tải bản đầy đủ - 0 (trang)
Chapter 6. BRANCHING STATEMENTS AND LOGICAL OPERATORS

Chapter 6. BRANCHING STATEMENTS AND LOGICAL OPERATORS

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

anotherwaytomakeachoice,andthelogicaloperators,which

letyoucombinetwotestsintoone.



TheifStatement

WhenaC++programmustchoosewhetherornottotakea

particularaction,youusuallyimplementthechoicewithanif

statement.Theifcomesintwoforms:ifandifelse.Let's

investigatethesimpleiffirst.It'smodeledafterordinary

English,asin"IfyouhaveaCaptainCookiecard,yougetafree

cookie."Theifstatementdirectsaprogramtoexecutea

statementorstatementblockifatestconditionistrueandto

skipthatstatementorblockiftheconditionisfalse.Thus,an

ifstatementletsaprogramdecidewhetheraparticular

statementshouldbeexecuted.

Thesyntaxissimilartothewhilesyntax:

if(test-condition)

statement

Atruetest-conditioncausestheprogramtoexecutestatement,

whichcanbeasinglestatementorablock.Afalsetestconditioncausestheprogramtoskipstatement.(SeeFigure

6.1.)Aswithlooptestconditions,aniftestconditionis

typecasttoaboolvalue,sozerobecomesfalseandnonzero

becomestrue.Theentireifconstructioncountsasasingle

statement.



Figure6.1.Theifstatement.



Mostoften,test-conditionisarelationalexpressionsuchas

thoseusedtocontrolloops.Suppose,forexample,youwanta

programthatcountsthespacesintheinputaswellasthetotal

numberofcharacters.Youcanusecin.get(char)inawhile

looptoreadthecharactersandthenuseanifstatementto

identifyandcountthespacecharacters.Listing6.1doesjust

that,usingtheperiodtorecognizetheendofasentence.



Listing6.1if.cpp



//if.cpp--usingtheifstatement

#include

usingnamespacestd;



intmain()

{

charch;

intspaces=0;

inttotal=0;

cin.get(ch);

while(ch!='.')//quitatendofsentence

{

if(ch=='')//checkifchisaspace

spaces++;

total++;//doneeverytime

cin.get(ch);

}

cout<
cout<<"characterstotalinsentence\n";

return0;

}

Here'ssomesampleoutput:



Theballoonistwasanairhead

withloftygoals.

6spaces,46characterstotalinsentence

Asthecommentsindicate,thespaces++;statementis

executedonlywhenchisaspace.Becauseitisoutsidetheif

statement,thetotal++;statementisexecutedeveryloop

cycle.Notethatthetotalcountincludesthenewlinecharacter

generatedbypressingEnter.



TheifelseStatement

Whiletheifstatementletsaprogramdecidewhethera

particularstatementorblockisexecuted,theifelse

statementletsaprogramdecidewhichoftwostatementsor

blocksisexecuted.It'saninvaluablestatementforcreating

alternativecoursesofaction.TheC++ifelseismodeled

aftersimpleEnglish,asin"IfyouhaveaCaptainCookiecard,

yougetaCookiePlusPlus,elseyoujustgetaCookie

d'Ordinaire."Theifelsestatementhasthisgeneralform:

if(test-condition)

statement1

else

statement2

Iftest-conditionistrueornonzero,theprogramexecutes



statement1andskipsoverstatement2.Otherwise,whentestconditionisfalseorzero,theprogramskipsstatement1and

executesstatement2instead.Sothecodefragment



if(answer==1492)

cout<<"That'sright!\n";

else

cout<<"You'dbetterreviewChapter1again.\n";

printsthefirstmessageifansweris1492andprintsthesecond

messageotherwise.Eachstatementcanbeeitherasingle

statementorastatementblockdelimitedbybraces.(See

Figure6.2.)Theentireifelseconstructcountssyntactically

asasinglestatement.



Figure6.2.Theifelsestatement.



Forexample,supposeyouwanttoalterincomingtextby

scramblingtheletterswhilekeepingthenewlinecharacter

intact.Thatway,eachlineofinputisconvertedtoanoutput

lineofequallength.Thismeansyouwanttheprogramtotake

onecourseofactionfornewlinecharactersandadifferent

courseofactionforallothercharacters.AsListing6.2shows,

ifelsemakesthistaskeasy.



Listing6.2ifelse.cpp



//ifelse.cpp--usingtheifelsestatement

#include

usingnamespacestd;

intmain()

{

charch;



cout<<"Type,andIshallrepeat.\n";

cin.get(ch);

while(ch!='.')

{

if(ch=='\n')

cout<


else

cout<<++ch;//doneotherwise

cin.get(ch);

}

//trych+1insteadof++chforinterestingeffect

cout<<"\nPleaseexcusetheslightconfusion.\n";

return0;

}

Here'ssomesampleoutput:

Type,andIshallrepeat.

Iamextraordinarilypleased

J!bn!fyusbpsejobsjmz!qmfbtfe

tousesuchapowerfulcomputer.

up!vtf!tvdi!b!qpxfsgvm!dpnqvufs

Pleaseexcusetheslightconfusion.

Notethatoneoftheprogramcommentssuggeststhatchanging

++chtoch+1hasaninterestingeffect.Canyoudeducewhatit

willbe?Ifnot,tryitoutandthenseeifyoucanexplainwhat's



happening.(Hint:Thinkabouthowcouthandlesdifferent

types.)



FormattingYourifelseStatements

Keepinmindthatthetwoifelsealternativesmustbesingle

statements.Ifyouneedmorethanonestatement,usebraces

tocollectthemintoasingleblockstatement.Unlikesome

languages,suchasBASICorFORTRAN,C++doesnot

automaticallyconsidereverythingbetweenifandelseablock,

soyouhavetousebracestomakethestatementsablock.The

followingcode,forexample,producesacompilererror.The

compilerseesitasasimpleifstatementthatendswiththe

zorro++;statement.Thenthereisacoutstatement.Sofar,so

good.Butthenthereiswhatthecompilerperceivesasan

unattachedelse,andthatisflaggedasasyntaxerror.

if(ch=='Z')

zorro++;//ifendshere

cout<<"AnotherZorrocandidate\n";

else//wrong

dull++;

cout<<"NotaZorrocandidate\n";

Addthebracestoconvertthecodetowhatyouwant:

if(ch=='Z')



{//iftrueblock

zorro++;

cout<<"AnotherZorrocandidate\n";

}

else

{//iffalseblock

dull++;

cout<<"NotaZorrocandidate\n";

}

BecauseC++isafree-formlanguage,youcanarrangethe

bracesasyoulike,aslongastheyenclosethestatements.The

precedingcodeshowsonepopularformat.Here'sanother:

if(ch=='Z'){

zorro++;

cout<<"AnotherZorrocandidate\n";

}

else{

dull++;

cout<<"NotaZorrocandidate\n";



}

Thefirstformemphasizestheblockstructureforthe

statements,whereasthesecondformmorecloselytiesthe

blockstothekeywordsifandelse.Eitherstyleisclearand

consistentandshouldserveyouwell;however,youmay

encounteraninstructororemployerwithstrongandspecific

viewsonthematter.



TheifelseifelseConstruction

Computerprograms,likelife,mightpresentyouwithachoice

ofmorethantwoselections.YoucanextendtheC++ifelse

statementtomeetthatneed.Theelse,you'veseen,shouldbe

followedbyasinglestatement,whichcanbeablock.Because

anifelsestatementitselfisasinglestatement,itcanfollow

anelse:

if(ch=='A')

a_grade++;//alternative#1

else

if(ch=='B')//alternative#2

b_grade++;//subalternative#2a

else

soso++;//subalternative#2b



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

Chapter 6. BRANCHING STATEMENTS AND LOGICAL OPERATORS

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

×