0% found this document useful (0 votes)
91 views

For, While and Do While Loops in C - Cprogramming

Loops allow code to be repeatedly executed. There are three types of loops in C: for, while, and do-while. For loops initialize a variable, specify a condition, and update the variable. While loops continuously execute while a condition is true. Do-while loops execute the code block at least once and then continue to loop while the condition is true. Break and continue statements can be used to control the flow of loops.

Uploaded by

afnaanqurreshi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

For, While and Do While Loops in C - Cprogramming

Loops allow code to be repeatedly executed. There are three types of loops in C: for, while, and do-while. For loops initialize a variable, specify a condition, and update the variable. While loops continuously execute while a condition is true. Do-while loops execute the code block at least once and then continue to loop while the condition is true. Break and continue statements can be used to control the flow of loops.

Uploaded by

afnaanqurreshi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Lesson3:Loops

ByAlexAllain

Loopsareusedtorepeatablockofcode.Beingabletohaveyourprogramrepeatedlyexecuteablockof
codeisoneofthemostbasicbutusefultasksinprogrammingmanyprogramsorwebsitesthatproduce
extremelycomplexoutput(suchasamessageboard)arereallyonlyexecutingasingletaskmanytimes.
(Theymaybeexecutingasmallnumberoftasks,butinprinciple,toproducealistofmessagesonly
requiresrepeatingtheoperationofreadinginsomedataanddisplayingit.)Now,thinkaboutwhatthis
means:aloopletsyouwriteaverysimplestatementtoproduceasignificantlygreaterresultsimplyby
repetition.

Onecaveat:beforegoingfurther,youshouldunderstandtheconceptofC'strueandfalse,becauseitwillbenecessarywhen
workingwithloops(theconditionsarethesameaswithifstatements).Thisconceptiscoveredintheprevioustutorial.
Therearethreetypesofloops:for,while,anddo..while.Eachofthemhastheirspecificuses.Theyarealloutlinedbelow.
FORforloopsarethemostusefultype.Thesyntaxforaforloopis

for(variableinitializationconditionvariableupdate){
Codetoexecutewhiletheconditionistrue
}
Thevariableinitializationallowsyoutoeitherdeclareavariableandgiveitavalueorgiveavaluetoanalreadyexisting
variable.Second,theconditiontellstheprogramthatwhiletheconditionalexpressionistruetheloopshouldcontinueto
repeatitself.Thevariableupdatesectionistheeasiestwayforaforlooptohandlechangingofthevariable.Itispossibleto
dothingslikex++,x=x+10,orevenx=random(5),andifyoureallywantedto,youcouldcallotherfunctionsthatdo
nothingtothevariablebutstillhaveausefuleffectonthecode.Noticethatasemicolonseparateseachofthesesections,that
isimportant.Alsonotethateverysingleoneofthesectionsmaybeempty,thoughthesemicolonsstillhavetobethere.Ifthe
conditionisempty,itisevaluatedastrueandtheloopwillrepeatuntilsomethingelsestopsit.
Example:
#include<stdio.h>
intmain()
{
intx
/*Theloopgoeswhilex<10,andxincreasesbyoneeveryloop*/
for(x=0x<10x++){
/*Keepinmindthattheloopconditionchecks
theconditionalstatementbeforeitloopsagain.
consequently,whenxequals10theloopbreaks.
xisupdatedbeforetheconditionischecked.*/
printf("%d\n",x)
}
getchar()
}
Thisprogramisaverysimpleexampleofaforloop.xissettozero,whilexislessthan10itcallsprintftodisplaythevalueof
thevariablex,anditadds1toxuntiltheconditionismet.Keepinmindalsothatthevariableisincrementedafterthecode
intheloopisrunforthefirsttime.
WHILEWHILEloopsareverysimple.Thebasicstructureis

while(condition){Codetoexecutewhiletheconditionistrue}Thetruerepresentsabooleanexpressionwhichcouldbex
==1orwhile(x!=7)(xdoesnotequal7).Itcanbeanycombinationofbooleanstatementsthatarelegal.Even,(whilex
==5||v==7)whichsaysexecutethecodewhilexequalsfiveorwhilevequals7.Noticethatawhileloopislikeastripped
downversionofaforloopithasnoinitializationorupdatesection.However,anemptyconditionisnotlegalforawhile
loopasitiswithaforloop.
Example:
#include<stdio.h>
intmain()
{
intx=0/*Don'tforgettodeclarevariables*/

while(x<10){/*Whilexislessthan10*/
printf("%d\n",x)
x++/*Updatexsotheconditioncanbemeteventually*/
}
getchar()
}
Thiswasanothersimpleexample,butitislongerthantheaboveFORloop.Theeasiestwaytothinkoftheloopisthatwhen
itreachesthebraceattheenditjumpsbackuptothebeginningoftheloop,whichcheckstheconditionagainanddecides
whethertorepeattheblockanothertime,orstopandmovetothenextstatementaftertheblock.
DO..WHILEDO..WHILEloopsareusefulforthingsthatwanttoloopatleastonce.Thestructureis
do{
}while(condition)
Noticethattheconditionistestedattheendoftheblockinsteadofthebeginning,sotheblockwillbeexecutedatleastonce.
Iftheconditionistrue,wejumpbacktothebeginningoftheblockandexecuteitagain.Ado..whileloopisalmostthesame
asawhileloopexceptthattheloopbodyisguaranteedtoexecuteatleastonce.Awhileloopsays"Loopwhiletheconditionis
true,andexecutethisblockofcode",ado..whileloopsays"Executethisblockofcode,andthencontinuetoloopwhilethe
conditionistrue".
Example:
#include<stdio.h>
intmain()
{
intx
x=0
do{
/*"Hello,world!"isprintedatleastonetime
eventhoughtheconditionisfalse*/
printf("Hello,world!\n")
}while(x!=0)
getchar()
}
Keepinmindthatyoumustincludeatrailingsemicolonafterthewhileintheaboveexample.Acommonerroristoforget
thatado..whileloopmustbeterminatedwithasemicolon(theotherloopsshouldnotbeterminatedwithasemicolon,
addingtotheconfusion).Noticethatthisloopwillexecuteonce,becauseitautomaticallyexecutesbeforecheckingthe
condition.

BreakandContinue

Twokeywordsthatareveryimportanttoloopingarebreakandcontinue.Thebreakcommandwillexitthemost
immediatelysurroundingloopregardlessofwhattheconditionsoftheloopare.Breakisusefulifwewanttoexitaloop
underspecialcircumstances.Forexample,let'ssaytheprogramwe'reworkingonisatwopersoncheckersgame.Thebasic
structureoftheprogrammightlooklikethis:
while(true)
{
take_turn(player1)
take_turn(player2)
}
Thiswillmakethegamealternatebetweenhavingplayer1andplayer2taketurns.Theonlyproblemwiththislogicisthat
there'snowaytoexitthegametheloopwillrunforever!Let'strysomethinglikethisinstead:
while(true)
{
if(someone_has_won()||someone_wants_to_quit()==TRUE)
{break}
take_turn(player1)
if(someone_has_won()||someone_wants_to_quit()==TRUE)
{break}
take_turn(player2)
}
Thiscodeaccomplisheswhatwewanttheprimaryloopofthegamewillcontinueundernormalcircumstances,butundera
specialcondition(winningorexiting)theflowwillstopandourprogramwilldosomethingelse.
Continueisanotherkeywordthatcontrolstheflowofloops.Ifyouareexecutingaloopandhitacontinuestatement,theloop
willstopitscurrentiteration,updateitself(inthecaseofforloops)andbegintoexecuteagainfromthetop.Essentially,the
continuestatementissaying"thisiterationoftheloopisdone,let'scontinuewiththeloopwithoutexecutingwhatevercode
comesafterme."Let'ssaywe'reimplementingagameofMonopoly.Likeabove,wewanttousealooptocontrolwhoseturn
itis,butcontrollingturnsisabitmorecomplicatedinMonopolythanincheckers.Thebasicstructureofourcodemightthen
looksomethinglikethis:
for(player=1someone_has_won==FALSEplayer++)
{
if(player>total_number_of_players)
{player=1}
if(is_bankrupt(player))
{continue}
take_turn(player)
}
Thisway,ifoneplayercan'ttakeherturn,thegamedoesn'tstopforeverybodywejustskipherandkeepgoingwiththe
nextplayer'sturn.
Stillnotgettingit?Askanexpert!
Quizyourself
Previous:IfStatements
Next:Functions
BacktoCTutorialIndex

You might also like