Tải bản đầy đủ - 0 (trang)
Chapter 6. C Control Statements: Looping

Chapter 6. C Control Statements: Looping

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

Writingfunctionsthathavereturnvalues

Powerful,intelligent,versatile,anduseful!Mostofuswouldn't

mindbeingdescribedthatway.WithC,there'satleastthe

chanceofhavingourprogramsdescribedthatway.Thetrickis

controllingtheflowofaprogram.Accordingtocomputer

science(whichisthescienceofcomputersandnotscienceby

computers…yet),agoodlanguageshouldprovidethesethree

formsofprogramflow:

Executingasequenceofstatements

Repeatingasequenceofstatementsuntilsomeconditionis

met(looping)

Usingatesttodecidebetweenalternativesequences

(branching)

Thefirstformyouknowwell;allthepreviousprogramshave

consistedofasequenceofstatements.Thewhileloopisone

exampleofthesecondform.Thischaptertakesacloserlookat

thewhileloopalongwithtwootherloopstructuresforanddo

while.Thefinalform,choosingbetweendifferentpossible

coursesofaction,makesaprogrammuchmore"intelligent"

andincreasestheusefulnessofacomputerenormously.Sadly,

you'llhavetowaitachapterbeforebeingentrustedwithsuch

power.Thechapteralsointroducesarraysbecausetheygive

yousomethingtodowithyournewknowledgeofloops.In

addition,thechaptercontinuesyoureducationaboutfunctions.

Let'sbeginbyreviewingthewhileloop.



RevisitingthewhileLoop

Youarealreadysomewhatfamiliarwiththewhileloop,butlet's

reviewitwithaprogramthatsumsintegersenteredfromthe

keyboard(seeListing6.1).Thisexamplemakesuseofthe

returnvalueofscanf()toterminateinput.



Listing6.1.Thesumming.cProgram



/*summing.c--sumsintegersenteredinteractively*/

#include

intmain(void)

{

longnum;

longsum=0L;/*initializesumtozero*/

intstatus;



printf("Pleaseenteranintegertobesummed");

printf("(qtoquit):");

status=scanf("%ld",&num);

while(status==1)/*==means"isequalto"*/



{

sum=sum+num;

printf("Pleaseenternextinteger(qtoquit):");

status=scanf("%ld",&num);

}

printf("Thoseintegerssumto%ld.\n",sum);



return0;

}



Listing6.1usestypelongtoallowforlargernumbers.For

consistency,theprograminitializessumto0L(typelongzero)

ratherthanto0(typeintzero),eventhoughC'sautomatic

conversionsenableyoutouseaplain0.

Hereisasamplerun:



Pleaseenteranintegertobesummed(qtoquit):44



Pleaseenternextinteger(qtoquit):33

Pleaseenternextinteger(qtoquit):88

Pleaseenternextinteger(qtoquit):121

Pleaseenternextinteger(qtoquit):q

Thoseintegerssumto286.



ProgramComments

Let'slookatthewhileloopfirst.Thetestconditionforthisloop

isthefollowingexpression:



status==1



The==operatorisC'sequalityoperator;thatis,thisexpression

testswhetherstatusisequalto1.Don'tconfuseitwithstatus

=1,whichassigns1tostatus.Withthestatus==1test

condition,thelooprepeatsaslongasstatusis1.Foreach

cycle,theloopaddsthecurrentvalueofnumtosum,sothatsum



maintainsarunningtotal.Whenstatusgetsavalueotherthan

1,theloopterminates,andtheprogramreportsthefinalvalue

ofsum.

Fortheprogramtoworkproperly,itshouldgetanewvaluefor

numoneachloopcycle,anditshouldresetstatusoneach

cycle.Theprogramaccomplishesthisbyusingtwodistinct

featuresofscanf().First,itusesscanf()toattempttoreada

newvaluefornum.Second,itusesthescanf()returnvalueto

reportonthesuccessofthatattempt.RecallfromChapter4,

"CharacterStringsandFormattedInput/Output,"thatscanf()

returnsthenumberofitemssuccessfullyread.Ifscanf()

succeedsinreadinganinteger,itplacestheintegerintonum

andreturnsthevalue1,whichisassignedtostatus.(Notethat

theinputvaluegoestonum,nottostatus.)Thisupdatesboth

numandthevalueofstatus,andthewhileloopgoesthrough

anothercycle.Ifyourespondwithnonnumericinput,suchasq,

scanf()failstofindanintegertoread,soitsreturnvalueand

statuswillbe0.Thatterminatestheloop.Theinputcharacter

q,becauseitisn'tanumber,isplacedbackintotheinput

queue;itdoesnotgetread.(Actually,anynonnumericinput,

notjustq,terminatestheloop,butaskingtheusertoenterqis

asimplerinstructionthanaskingtheusertoenternonnumeric

input.)

Ifscanf()runsintoaproblembeforeattemptingtoconvertthe

value(forexample,bydetectingtheendofthefileorby

encounteringahardwareproblem),itreturnsthespecialvalue

EOF,whichtypicallyisdefinedas-1.Thisvalue,too,willcause

thelooptoterminate.

Thisdualuseofscanf()getsaroundatroublesomeaspectof

interactiveinputtoaloop:Howdoyoutelltheloopwhento

stop?Suppose,forinstance,thatscanf()didnothaveareturn

value.Then,theonlythingthatwouldchangeoneachloopis

thevalueofnum.Youcouldusethevalueofnumtoterminate

theloop,using,say,num>0(numgreaterthan0)ornum!=0



(numnotequalto0)asatestcondition,butthispreventsyou

fromenteringcertainvalues,suchas3or0,asinput.Instead,

youcouldaddnewcodetotheloop,suchasasking"Doyou

wishtocontinue?"ateachcycle,andthentesttosee

whethertheuserenteredy.Thisisabitclunkyandslowsdown

input.Usingthereturnvalueofscanf()avoidstheseproblems.

Nowlet'stakeacloserlookattheprogramstructure.Youcan

summarizeitasfollows:



initializesumto0

promptuser

readinput

whiletheinputisaninteger,

addtheinputtosum,

promptuser,

thenreadnextinput

afterinputcompletes,printsum



This,incidentally,isanexampleofpseudocode,whichistheart



ofexpressingaprograminsimpleEnglishthatparallelsthe

formsofacomputerlanguage.Pseudocodeisusefulforworking

outthelogicofaprogram.Afterthelogicseemsright,youcan

translatethepseudocodetotheactualprogrammingcode.One

advantageofpseudocodeisthatitenablesyoutoconcentrate

onthelogicandorganizationofaprogramandsparesyoufrom

simultaneouslyworryingabouthowtoexpresstheideasina

computerlanguage.Here,forexample,youcanuseindentation

toindicateablockofcodeandnotworryaboutCsyntax

requiringbraces.Anotheradvantageisthatpseudocodeisnot

tiedtoaparticularlanguage,sothesamepseudocodecanbe

translatedintodifferentcomputerlanguages.

Anyway,becausethewhileloopisanentry-conditionloop,the

programmustgettheinputandcheckthevalueofstatus

beforeitgoestothebodyoftheloop.Thatiswhytheprogram

hasascanf()beforethewhile.Forthelooptocontinue,you

needareadstatementinsidetheloopsothatitcanfindoutthe

statusofthenextinput.Thatiswhytheprogramalsohasa

scanf()statementattheendofthewhileloop;itreadiesthe

loopforitsnextiteration.Youcanthinkofthefollowingasa

standardformatforaloop:



getfirstvaluetobetested

whilethetestissuccessful

processvalue

getnextvalue



C-StyleReadingLoop

Listing6.1couldbewritteninPascal,BASIC,orFORTRANalong

thesamedesigndisplayedinthepseudocode.C,however,

offersashortcut.Theconstruction



status=scanf("%ld",&num);

while(status==1)

{

/*loopactions*/

status=scanf("%ld",&num);

}



canbereplacedbythefollowing:



while(scanf("%ld",&num)==1)

{

/*loopactions*/

}



Thesecondformusesscanf()intwodifferentways

simultaneously.First,thefunctioncall,ifsuccessful,placesa

valueinnum.Second,thefunction'sreturnvalue(whichis1or

0andnotthevalueofnum)controlstheloop.Becausetheloop

conditionistestedateachiteration,scanf()iscalledateach

iteration,providinganewnumandanewtest.Inotherwords,

C'ssyntaxfeaturesletyoureplacethestandardloopformat

withthefollowingcondensedversion:



whilegettingandtestingthevaluesucceeds

processthevalue



Nowlet'stakeamoreformallookatthewhilestatement.



ThewhileStatement

Thisisthegeneralformofthewhileloop:



while(expression)

statement



Thestatementpartcanbeasimplestatementwitha

terminatingsemicolon,oritcanbeacompoundstatement

enclosedinbraces.

Sofar,theexampleshaveusedrelationalexpressionsforthe

expressionpart;thatis,expressionhasbeenacomparisonof

values.Moregenerally,youcanuseanyexpression.If

expressionistrue(or,moregenerally,nonzero),thestatement

isexecutedonceandthentheexpressionistestedagain.This

cycleoftestandexecutionisrepeateduntilexpression

becomesfalse(zero).Eachcycleiscalledaniteration(see

Figure6.1).



Figure6.1.Structureofthewhileloop.



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

Chapter 6. C Control Statements: Looping

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

×