for loops
A for
loop has a slightly more complicated syntax than the while
or do while
loops as it takes three parts to initialize. Have a look at the code first, then we will break it apart:
for(int i = 0; i < 10; i++){ //Something that needs to happen 10 times goes here }
The slightly more complicated form of the for
loop is clearer when put like this:
for(declaration and initialization; condition; change after each pass through loop).
To clarify further, we have the following:
declaration and initialization
: We create a newint
variable,i
,condition
: Just like the other loops, it refers to the condition that must evaluate to true for the loop to continue.change after each pass through the loop
: In the example,i++
means that 1 is added/incremented toi
on each pass. We could also usei--
to reduce/decrementi
at each pass:for(int i = 10; i > 0; i--){ // countdown...