1. Technology

Determinate Loops


Often it's useful to be able to use the same lines of code again and again until a certain outcome is reached. This is done by using a loop. A determinate loop is one that knows the number of times it is going to iterate (i.e., how many times the code it contains is going to execute). The determinate loop in Java is the for loop.

The for loop

The syntax for the for loop is as follows:

for (int i=1; i <20; i++)
   //the code in here get executed every time it loops

The block of code contained with the for loop is executed again and again until the specified number of iterations is reached. As you can see the iterations of the for loop is controlled by an int variable. This variable can be named anything but typically it's simply called 'i'. The first part declares the int variable and gives it a value, next a condition is specified for the int variable to reach (e.g., in the code above i must get to 19 in order for the loop to stop), and finally how the value of i changes.

It's just as simple to get a for loop to count downwards:

for(int k=20; k>0; k--)

The for-each loop

The for loop can be extending to work over arrays and collections. The syntax changes slightly because of an interator variable it's the relationship between the array or collection and the type of variables it contains. For example, to iterate all the int elements in an array:

int[] randomNumbers = {1,4,7,9,3,2,6,99};

for(int i: randomNumbers)

To see a for loop in action have a look at the Going Loopy example program.

  1. About.com
  2. Technology
  3. Java
  4. Java Syntax
  5. Control Flow
  6. Java Syntax: Determinate Loops

©2014 About.com. All rights reserved.