loop statement
Languageloop
InClanguage,therearethreetypesofloopstatements:forstatement,whilestatementanddoWhilestatement.Therespectiveintroductionsareasfollows:
for
Forisacurrenttypeloopstatement,whichwellreflectsthethreeproblemsthatshouldbepaidattentiontointhecorrectexpressionofloopstructure:
⑴Initializationofcontrolvariables.
⑵Circulationconditions.
(3)Theupdateofloopcontrolvariables.
forexpression
Expression1:Generallyanassignmentexpression,whichassignsaninitialvaluetothecontrolvariable;
p>Expression2:Relationalexpressionorlogicalexpression,loopcontrolcondition;
Expression3:Generallyanassignmentexpression,incrementordecrementthecontrolvariable.
Statement:loopbody,whentherearemultiplesentences,compoundsentencesmustbeused.
Theformatoftheforstatementis:
For(expression1;expression2;expression3)statement:/*Loopbody*/
Theexecutionprocessoftheforstatementisasfollows:
①Firstassignaninitialvaluetoexpression1;
②Judgingwhetherexpression2meetsthegivencondition,ifitsvalueisnot0,andtheloopconditionismet,thestatementintheloopisexecuted,thenexpression3isexecuted,andthesecondloopisentered,andthenexpression2isjudged...;Otherwise,itisjudgedthatthevalueofexpression2is0,andtheconditionisnotmet,theforloopisterminated,andthestatementaftertheloopbodyisexecuted.ThesyntaxflowofforstatementisshowninFigure1below:
Examplequestion:
#includeintmain(){intn,nu;Nu=0;for(n=1;n<=200;n++)nu+=n;printf("nu=%d\n",nu);return0;}
CompileandexecuteAfterthat,thescreendisplays:
nu=20100
Intheprogram,thethreeexpressionsintheparenthesesoftheforstatementare:n=1;n<=200;n++.Expression1,n=1istoassignaninitialvalueton,andexpression2isarelationalexpression.Whennislessthanorequalto200,theexpressionsarealltrue,andthestatementnu+=nintheloopbodyisexecuted;(ienu=nu+n;),andthenexecuteexpression3(n++)toenterthenextroundofloop;ifnisgreaterthan200,expression2isfalse,terminatetheloop,executetheprintf()statement,andprintoutonthescreen:nu=20100.
Theusageofseveralspecialforstatements:
Thethreeexpressionsintheforbracketscanbeomitted,andthemiddleisomitted.Theexpressionmeansunconditionalloop
while
►whilestructureloopiswhentypeloop,whichisgenerallyusedwhenthenumberofloopsisnotknown.Whatmaintainstheloopisaconditionalexpression,theloopbodyisexecutediftheconditionissatisfied,andtheloopisexitediftheconditionisnotsatisfied.
Theformatofthewhilestatementis:
►while(conditionalexpression)
►Loopbody
►Theconditionalexpressionmustbejudgedeverytimebeforetheloopbodyisexecuted.
Theexpressionhereistheconditionofwhethertheloopcancontinue,andthestatementisthebodyoftheloop.Aslongastheexpressionistrue,thestatementinsidetheloopisexecuted.Otherwise,theloopisterminatedandthestatementoutsidetheloopisexecuted.
Examplequestion:f7_2.c
#ncludeintmain(){intu,v,temp;puts("pleaseEntertwonon-negativeintegers:");scanf("%d%d",&u,&v);while(v!=0)temp=u%v;/*Loopinsidesentence*/u=v;/*In-loopstatement*/v=temp;/*In-loopstatement*/Printf("Thegreatestcommondivisoris:%d\n",u);return0;}
Compileandexecutetheresult,thescreendisplays:
Pleaseentertwonon-negativeintegers:
Ifyouenterfromthekeyboard:15035andpressEnter,thescreendisplays:
Thegreatestcommondivisoris:5
Intheprogram,therearethreestatementsinthewhileloop,whichshouldbeenclosedinbracestoindicateablockofstatements.Whentheexpressionv!=0istrue,theprogramloopsthroughthethreestatementsintheloop,untilv!=0isfalse,terminatetheloop,executetheprintf()statement,anddisplaythegreatestcommondivisoronthescreen.
dowhile
►Thestructureofthedo...whilestatementisanuntiltypeloop,whichisalsousedwhenthenumberofloopsisunknown.Thedifferencebetweendo...whileandwhileisthatthedo...whilestructureisexecutedoncetheloopbodyisexecutedandthentheconditionisjudged.
Theformatofthedowhilestatementis:
►do
►Loopbody
►while(conditionalexpression);
►Eachtimetheloopbodyisexecuted,thedo...whilestructuremustjudgetheconditionalexpression.
Aftertheprogramentersthedowhileloop,executethestatementintheloopfirst,andthendeterminethetrueorfalseoftheexpression,ifitistrue,proceedtothenextloop,otherwiseitwillterminatetheloopifitisfalse.Thecharacteristicoftheloopstatementisthatthestatementintheloopbodyisexecutedoncewhentheexpressionisfalse.
Thesyntaxflowofthedowhilestatementisshowninthefollowingfigure:
Ingeneral,theforandwhileloopsareatthetopTheuppertestloopterminationcondition,andthedowhileloopisafter,thetestisperformedatthebottom,sotheloopbodymustbeexecutedatleastonce.
Usingthecharacteristicsofthedowhileloop,youcanwriteamenuprogram.
Examplequestion:
#includeintmain(){intch;printf("1.Inputrecord\n");Printf("2.deleterecord\n");printf("3.displayrecord\n");printf("pleaseselect:\n");doch=getchar();case{switch(ch)'1':printf("enterrecord\n");break;case'2':printf("deleterecords\n");break;case'3':printf("displayrecord\n");break;default:printf("Wrongselection!\n");}while(ch!='1'&&ch!='2'&&ch!='3');}
Thedifferencebetweenwhileanddowhile
►Assumethattheconditionalexpressionisnotestablishedatthebeginning.
►Theloopbodyofthewhilestructurewillnotrunagain.
►Theloopbodyofthedo...whilestructurerunsagain.
Theexecutionprocessofthisprogramistoreceivetheuser'schoicethroughthefirststatementch=getchar()inthedowhileloop,andthesecondstatementswitchtodeterminewhethertheuserinputis'1','2','3',ifitisnot,itwilldisplay"Wrongselection!".Theprogramtakesadvantageofthecharacteristicsofthedowhilestatement,firstexecutesthestatementintheloopbodyonce,andthenusestheexpressionch!='1'&&ch!='2'&&ch!='3'tocyclethroughthejudgmentoftheuserKeyboardinput,aslongasitisnot'1','2',or'3',theprogramwillalwaysloophere.
Thisprogramexampleisjusttoillustratetheusageofthedowhilestatement.Intheactualapplicationofthemenuprogram,youmustwritethecorrespondingfunctiontobecalledafterthecolonofeachcasestatement.
Loopstatement
Theloopstatementistoexecutethesamestatementrepeatedlyaccordingtotheloopconditionuntiltheloopconditionisnotestablished.
Basic
ThefollowingloopstatementscanbeusedinVisualBasic\VBScript\VBA:
Do...Loop:When(orLoopuntil)theconditionisTrue.
While...Wend:LoopwhentheconditionisTrue.
..Next:Specifythenumberofloopsandusethecountertorunthestatementrepeatedly.
ForEach...Next:Repeatasetofstatementsforeachiteminthecollectionoreachelementinthearray.
Do
YoucanusetheDo...Loopstatementtorunthestatementblockmultipletimes(indefinitenumberoftimes).WhentheconditionisTrueorbeforetheconditionbecomesTrue,thestatementblockisexecutedrepeatedly.
RepeatthestatementwhentheconditionisTrue
TheWhilekeywordisusedtochecktheconditionintheDo...Loopstatement.Therearetwowaystocheckthecondition:checktheconditionbeforeenteringtheloop(asintheChkFirstWhileexamplebelow);orchecktheconditionaftertheloophasrunatleastonce(asintheChkLastWhileexamplebelow).IntheChkFirstWhileprocess,iftheinitialvalueofmyNumissetto9insteadof20,thestatementintheloopbodywillneverbeexecuted.IntheChkLastWhileprocess,thestatementintheloopbodywillonlybeexecutedonce,becausetheconditionisalreadyFalsewhenchecked.
SubChkFirstWhile()
Dimcounter,myNum
counter=0
myNum=20
DoWhilemyNum>10
myNum=myNum-1
counter=counter+1
Loop
MsgBoxlooprepeated&counter×.
EndSub
SubChkLastWhile()
Dimcounter,myNum
counter=0
myNum=9
Do
myNum=myNum-1
counter=counter+1
LoopWhilemyNum>10
MsgBoxlooprepeated&counter×.
EndSub
ExecutethestatementrepeatedlyuntiltheconditionbecomesTrue
TheUntilkeywordisusedtochecktheconditionintheDo...Loopstatement.Therearetwowaystocheckthecondition:checktheconditionbeforeenteringtheloop(asintheChkFirstUntilexamplebelow);orchecktheconditionaftertheloophasrunatleastonce(asintheChkLastUntilexamplebelow).AslongastheconditionisFalse,theloopwillbeperformed.
SubChkFirstUntil()
Dimcounter,myNum
counter=0
myNum=20
DoUntilmyNum=10
myNum=myNum-1
counter=counter+1
Loop
MsgBoxlooprepeats&counter×.
EndSub
SubChkLastUntil()
Dimcounter,myNum
counter=0
myNum=1
Do
myNum=myNum+1
counter=counter+1
LoopUntilmyNum=10
MsgBoxlooprepeated&counter×.
EndSub
Exittheloop
ExitDostatementisusedtoexittheDo...Looploop.Becauseitisusuallyonlynecessarytoexittheloopinsomespecialcases(forexample,toavoidinfiniteloops),youcanusetheExitDostatementintheTrueblockoftheIf...Then...Elsestatement.IftheconditionisFalse,theloopwillrunasusual.
Inthefollowingexample,theinitialvalueofmyNumwillcauseanendlessloop.TheIf...Then...Elsestatementchecksthisconditiontopreventanendlessloop.
SubExitExample()
Dimcounter,myNum
counter=0
myNum=9
DoUntilmyNum=10
myNum=myNum-1
counter=counter+1
IfmyNum<10ThenExitDo
Loop
MsgBoxlooprepeated&counter×.
EndSub
While..Wend
..Wendstatementisprovidedforthosewhoarefamiliarwithitsusage.However,duetothelackofflexibilityofWhile...Wend,itisrecommendedtousetheDo...Loopstatement.
Next
..Nextstatementisusedtorunthestatementblockaspecifiednumberoftimes.Thecountervariableisusedintheloop,andthevalueofthevariableincreasesordecreaseswitheachloop.
Forexample,thefollowingexamplerepeatstheprocedureMyProc50times.TheForstatementspecifiesthecountervariablexanditsstartvalueandendvalue.TheNextstatementincrementsthecountervariablebyoneeachtime.
SubDoMyProc50Times()
DimxForx=1To50
MyProc
Next
EndSub
ThekeywordStepisusedtospecifythevalueofeachincreaseordecreaseofthecountervariable.Intheexamplebelow,thecountervariablejisincrementedby2eachtime.Aftertheloopisover,thevalueoftotalisthesumof2,4,6,8,and10.
SubTwosTotal()
Dimj,total
Forj=2To10Step2
total=total+j
Next
ThesumofMsgBoxis&total&;.
EndSub
Todecrementthecountervariable,setSteptoanegativevalue.Atthistime,theendvalueofthecountervariablemustbelessthanthestartvalue.Inthefollowingexample,thecountervariablemyNumisdecrementedby2eachtime.Aftertheloopends,thevalueoftotalisthesumof16,14,12,10,8,6,4,and2.
SubNewTotal()
DimmyNum,total
FormyNum=16To2Step-2
total=total+myNum
Next
ThesumofMsgBoxis&total&;.
EndSub
TheExitForstatementisusedtoexittheFor...Nextstatementbeforethecounterreachesitsendvalue.Becauseitisusuallyonlynecessarytoexittheloopinsomespecialcircumstances(forexample,whenanerroroccurs),youcanusetheExitForstatementintheTrueblockoftheIf...Then...Elsestatement.IftheconditionisFalse,theloopwillrunasusual.
UsingForEach...Next
ForEach...NextloopissimilartoFor...Nextloop.ForEach...Nextdoesnotrunthestatementaspecifiednumberoftimes,butrepeatsasetofstatementsforeachelementinthearrayoreachiteminthecollectionofobjects.Thisisveryusefulwhenyoudon'tknowthenumberofelementsintheset.
Inthefollowingexample,thecontentoftheDictionaryobjectisusedtoplacetextinmultipletextboxes:
;formsandelements
EasyLanguage
Easylanguageloopstatementsaredividedintothreetypesofcountingloops,judgmentloopsandloopjudgments
Countingloops
Thecommandsinthelooparerepeatedlyexecutedforthespecifiednumberoftimes.Theintegerparametervalueprovideddetermineshowmanytimestheexecutionwillberepeated.
Countingcyclefirst(cycletimes,cycletimesvariable)
Countingcycleend()
Judgingcycle
AccordingtoThevalueoftheprovidedlogicparameterdetermineswhethertoentertheloop.Ifthevalueoftheprovidedlogicparameteristrue,theprogramexecutesthenextcommandinsequenceandenterstheloop;otherwise,itjumpstothenextcommandofthe"JudgingLoopEnd"commandcorrespondingtothiscommandtojumpoutoftheloop.
Judgingthebeginningoftheloop(condition)
Judgingtheendoftheloop()
Judgingtheloop
Theendoftheloopjudgmentistheconditionoftheloop,Accordingtothevalueoftheprovidedlogicparameter,itisdecidedwhethertoreturntotheloopheadertocontinuetheloop.Iftheprovidedlogicparametervalueistrue,theprogramreturnstothecorresponding"loopjudgmentfirst"commandtocontinuetheloop,otherwise,executethenextcommandinordertoexittheprogramloop.
Firstofloopjudgment()
Endofloopjudgment(condition)
Latest: Finite state automata
Next: Photonic crystal fiber