Java Tutorial/Control Structures II - Looping

You can use loops to repeat the execution of a certain thing, without writing it out multiple times. There are several different loops you can use to meet your needs.

While Loops
While loops are the simplest kind of loops. They go as follows:

While the boolean is true, the "do..." section will be executed. Once it becomes false, the loop will exit. An example:

This displays the numbers 0 - 4 in the loop, and 5 outside of it.

Do-While Loops
Do-While loops have the structure like:

It will execute "do...", and then check if the boolean is true or false. Then, it repeats. This is just like a regular while loop, except it ensures the code is executed at least once. An example of its use:

This will print the numbers 2.5, 3.5, 4.5, and 5.5.

For Loops
For loops are used mostly when you want counters in your loop. The structure is:

The usual usage is:

As you can see, the loop first sets i to equal 0. Then, it checks that i is less than myNumber (before actually executing something). Then, it executes "do...". It increases i by 1. Then, it checks that i is less than myNumber again, executes "do...", etc.

(learn for-each loops in array section?)

Exercises

 * Make a for-loop that prints "Something" exactly 5 times.

Answer:

Another, more "wild" answer: