Tải bản đầy đủ - 0 (trang)
Chapter 7. C Control Statements: Branching and Jumps

Chapter 7. C Control Statements: Branching and Jumps

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

Thefamilyofcharacter-analysisfunctionsprovidedbythe

ctype.hheaderfile

AsyougrowmorecomfortablewithC,youwillprobablywantto

tacklemorecomplextasks.Whenyoudo,you'llneedwaysto

controlandorganizetheseprojects.Chasthetoolstomeet

theseneeds.You'vealreadylearnedtouseloopstoprogram

repetitivetasks.Inthischapter,you'lllearnaboutbranching

structuressuchasifandswitch,whichallowaprogramto

baseitsactionsonconditionsitchecks.Also,youare

introducedtoC'slogicaloperators,whichenableyoutotestfor

morethanonerelationshipinawhileorifcondition,andyou

lookatC'sjumpstatements,whichshifttheprogramflowto

anotherpartofaprogram.Bytheendofthischapter,you'll

haveallthebasicinformationyouneedtodesignaprogram

thatbehavesthewayyouwant.



TheifStatement

Let'sstartwithasimpleexampleofanifstatement,shownin

Listing7.1.Thisprogramreadsinalistofdailylow

temperatures(inCelsius)andreportsthetotalnumberof

entriesandthepercentagethatwerebelowfreezing(thatis,

belowzerodegreesCelsius).Itusesscanf()inalooptoread

inthevalues.Onceduringeachloopcycle,itincrementsa

countertokeeptrackofthenumberofentries.Anifstatement

identifiestemperaturesbelowfreezingandkeepstrackofthe

numberofbelow-freezingdaysseparately.



Listing7.1.Thecolddays.cProgram



//colddays.c--findspercentageofdaysbelowfreezing

#include

intmain(void)

{

constintFREEZING=0;

floattemperature;

intcold_days=0;

intall_days=0;



printf("Enterthelistofdailylowtemperatures.\n");



printf("UseCelsius,andenterqtoquit.\n");

while(scanf("%f",&temperature)==1)

{

all_days++;

if(temperature
cold_days++;

}

if(all_days!=0)

printf("%ddaystotal:%.1f%%werebelowfreezing.\n",



all_days,100.0*(float)cold_days/all_days);

if(all_days==0)

printf("Nodataentered!\n");



return0;

}



Hereisasamplerun:



Enterthelistofdailylowtemperatures.

UseCelsius,andenterqtoquit.

125-2.5068-3-10510q

10daystotal:30.0%werebelowfreezing.



Thewhilelooptestconditionusesthereturnvalueofscanf()

toterminatetheloopwhenscanf()encountersnonnumeric

input.Byusingfloatinsteadofintfortemperature,the

programisabletoacceptinputsuchas-2.5aswellas8.

Hereisthenewstatementinthewhileblock:



if(temperature
cold_days++;



Thisifstatementinstructsthecomputertoincreasecold_days

by1ifthevaluejustread(temperature)islessthanzero.

Whathappensiftemperatureisnotlessthanzero?Thenthe

cold_days++;statementisskipped,andthewhileloopmoves

ontoreadthenexttemperaturevalue.

Theprogramusestheifstatementtwomoretimestocontrol

theoutput.Ifthereisdata,theprogramprintstheresults.If

thereisnodata,theprogramreportsthatfact.(Soonyou'llsee

amoreelegantwaytohandlethispartoftheprogram.)

Toavoidintegerdivision,theexampleusesthecasttofloat

whenthepercentageisbeingcalculated.Youdon'treallyneed

thetypecastbecauseintheexpression100.0*cold_days/

all_days,thesubexpression100.0*cold_daysisevaluated

firstandisforcedintofloatingpointbytheautomatictype

conversionrules.Usingthetypecastdocumentsyourintent,

however,andhelpsprotecttheprogramagainstmisguided

revisions.

Theifstatementiscalledabranchingstatementorselection

statementbecauseitprovidesajunctionwheretheprogram

hastoselectwhichoftwopathstofollow.Thegeneralformis

this:



if(expression)

statement



Ifexpressionevaluatestotrue(nonzero),statementis

executed.Otherwise,itisskipped.Aswithawhileloop,

statementcanbeeitherasinglestatementorasingleblock

(alsotermedacompoundstatement).Thestructureisvery

similartothatofawhilestatement.Thechiefdifferenceisthat

inanifstatement,thetestand(possibly)theexecutionare

donejustonce,butinthewhileloop,thetestandexecution

canberepeatedseveraltimes.

Normally,expressionisarelationalexpression;thatis,it

comparesthemagnitudeoftwoquantities,asinthe

expressionsx>yandc==6.Ifexpressionistrue(xis

greaterthany,orcdoesequal6),thestatementisexecuted.

Otherwise,thestatementisignored.Moregenerally,any

expressioncanbeused,andanexpressionwitha0valueis

takentobefalse.

Thestatementportioncanbeasimplestatement,asinthe

example,oritcanbeacompoundstatementorblock,marked

offbybraces:



if(score>big)

printf("Jackpot!\n");//simplestatement



if(joe>ron)



{//compoundstatement

joecash++;

printf("Youlose,Ron.\n");

}



Notethattheentireifstructurecountsasasinglestatement,

evenwhenitusesacompoundstatement.



AddingelsetotheifStatement

Thesimpleformofanifstatementgivesyouthechoiceof

executingastatement(possiblycompound)orskippingit.C

alsoenablesyoutochoosebetweentwostatementsbyusing

theifelseform.Let'susetheifelseformtofixan

awkwardsegmentfromListing7.1.



if(all_days!=0)

printf("%ddaystotal:%.1f%%werebelowfreezing.\n",

all_days,100.0*(float)cold_days/all_days);

if(all_days==0)

printf("Nodataentered!\n");



Iftheprogramfindsthatall_daysisnotequalto0,itshould

knowthatdaysmustbe0withoutretesting,anditdoes.With

ifelse,youcantakeadvantageofthatknowledgeby

rewritingthefragmentthisway:



if(all_days!=0)

printf("%ddaystotal:%.1f%%werebelowfreezing.\n",

all_days,100.0*(float)cold_days/all_days);

else

printf("Nodataentered!\n");



Onlyonetestismade.Iftheiftestexpressionistrue,the

temperaturedataisprinted.Ifit'sfalse,thewarningmessageis

printed.

Notethegeneralformoftheifelsestatement:



if(expression)

statement1

else



statement2



Ifexpressionistrue(nonzero),statement1isexecuted.If

expressionisfalseorzero,thesinglestatementfollowingthe

elseisexecuted.Thestatementscanbesimpleorcompound.

Cdoesn'trequireindentation,butitisthestandardstyle.

Indentationshowsataglancethestatementsthatdependona

testforexecution.

Ifyouwantmorethanonestatementbetweentheifandthe

else,youmustusebracestocreateasingleblock.The

followingconstructionviolatesCsyntax,becausethecompiler

expectsjustonestatement(singleorcompound)betweenthe

ifandtheelse:



if(x>0)

printf("Incrementingx:\n");

x++;

else//willgenerateanerror

printf("x<=0\n");



Thecompilerseestheprintf()statementaspartoftheif

statement,anditseesthex++;statementasaseparate

statement,notaspartoftheifstatement.Itthenseesthe

elseasbeingunattachedtoanif,whichisanerror.Instead,

usethis:



if(x>0)

{

printf("Incrementingx:\n");

x++;

}

else

printf("x<=0\n");



Theifstatementenablesyoutochoosewhethertodoone

action.Theifelsestatementenablesyoutochoosebetween

twoactions.Figure7.1comparesthetwostatements.



Figure7.1.ifversusifelse.



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

Chapter 7. C Control Statements: Branching and Jumps

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

×