Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

C++FORLOOP

http://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm

Copyrighttutorialspoint.com

Aforloopisarepetitioncontrolstructurethatallowsyoutoefficientlywritealoopthatneedstoexecutea
specificnumberoftimes.

Syntax:
ThesyntaxofaforloopinC++is:
for(init;condition;increment)
{
statement(s);
}

Hereistheflowofcontrolinaforloop:
Theinitstepisexecutedfirst,andonlyonce.Thisstepallowsyoutodeclareandinitializeanyloop
controlvariables.Youarenotrequiredtoputastatementhere,aslongasasemicolonappears.
Next,theconditionisevaluated.Ifitistrue,thebodyoftheloopisexecuted.Ifitisfalse,thebodyof
theloopdoesnotexecuteandflowofcontroljumpstothenextstatementjustaftertheforloop.
Afterthebodyoftheforloopexecutes,theflowofcontroljumpsbackuptotheincrementstatement.
Thisstatementallowsyoutoupdateanyloopcontrolvariables.Thisstatementcanbeleftblank,aslong
asasemicolonappearsafterthecondition.
Theconditionisnowevaluatedagain.Ifitistrue,theloopexecutesandtheprocessrepeatsitself
bodyof loop, thenincrementstep, andthenagaincondition .Aftertheconditionbecomesfalse,thefor
loopterminates.

FlowDiagram:

Example:
#include<iostream>
usingnamespacestd;

intmain()
{
//forloopexecution
for(inta=10;a<20;a=a+1)
{
cout<<"valueofa:"<<a<<endl;
}

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:15
valueofa:16
valueofa:17
valueofa:18
valueofa:19

You might also like