Tuesday, April 16, 2013

The For loop


Loops allow us to perform a set of instructions repeatedly until a certain condition is reached.

A video game is basically a continuous loop that handles input, handles updates and draws - maybe 60 times per second!

There are a few different kinds of loops. This post is about the For-Loop, however all loops have some things in common:

  • A loop needs a start condition - where to start
  • A loop needs an end condition - where to end
  • A loop contains a body - the statements to execute repeatedly.

If a loop does not know where to end, we get an INFINITE LOOP and that's really no good.

The For-Loop
The for-loop is primed with the following information about the loop:

  • The value of the loop counter when the loop starts - initialization
  • The value that flags the end of the loop - termination
  • How the loop counter should be incremented on each pass of the loop - increment

Format of the syntax:

for (initialization; termination; increment) {
    statement(s)
}


Note:

  • The increment condition may also be a decrement condition.
  • The loop counter can begin at any value - for instance 0 or 1000 (it depends on the task).


The body of the loop is where we place the instructions which need to be repeated.

In the following example, the numbers 0 to 9 are printed to screen. The loop has been primed to start the counter variable at 0. The loop will continue while the counter variable is less than 10. The counter variable will be incremented on each pass of the loop.



In the following example, the numbers 10 to 0 are printed to screen. The loop has been primed to start the counter variable at 10. The loop will continue while the counter variable is greater than 0. The counter variable will be decremented on each pass of the loop.



"The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/ZtqqHM )

No comments:

Post a Comment