Java Tutorials:The for loop

The for loop

This loop is used if you know exactly how many times you want to perform a certain task. For example to print out the 2 times table you know you want to loop 10 times. The code to print out the 2 times table is listed below. It uses a for loop. Pay special attention to how the loop structure is set up.

Compile the above code and see what happens. This code shouldn’t pose you too many problems. The first line needs some explaining. The first part of the line in brackets sets up what is called the reference variable (always an integer), the second part is what is known as the break condition (if this condition isn’t met the loop is terminated) and the last part declares how the variable is to change after each cycle of the loop (in this case when the loop gets to the bottom 1 is added to the value of i).

So what happens? Simple, the computer reads the first line and sees that i is equal to 1. Then it tests the break condition, in this case i (1) is less than 11 so the loop is valid. Therefore it executes the code inside the brackets and then adds one to i, tests again, executes code, add 1 to i, tests again etc etc. Until the break condition fails. As soon as this occurs the computer ignores the loop from that point onwards and carries on with the rest of the program. Pretty easy so far, eh? Lets have a look at while loops.

The while loop

A while loop is usually used when you aren’t sure how many times you are going to have to carry something out. It can be used just like a for loop (I’m going to show you the above code using a while loop) but the resulting code looks more complicated. The above code but this time using a while loop is listed below:

The above code is in my opinion nowhere near as elegant as the for loop code. The variable get changed at the bottom of the loop! yuk! I prefer to keep it all together at the top. Use whatever you find easiest at this stage.

Another useful feature of the while loop is that you can use Boolean variables with it. For example to set up an loop using a Boolean variable you could enter

This code would loop until the if statement was executed. This is a very powerful feature of loops and you will definitely use it in the future. Another powerful feature of the while loop is indefinite loops. The only way of exiting one of these loops is by using the keyword break when you want to exit the loop. An example is given below:

This is often used in game programming when you want the game to run forever until the exit button is pressed/clicked. The exit button could be tested by the if statement and if it was detected to be pressed then the loop would exit and the game would stop.