Ok, Looping...so it's basically doing something while a certain condition is true. That sentence is basically one of the loops forms.
The for LoopOk, so the
for loop. This is a useful looping structure for traversing through arrays and such. Let's take a look at the syntax shall we?
java
for (int x = 0; x < 100; x++)
{
// statements to execute 100 times
}
The
for line, let's take a closer look at it...It starts with the
for keyword of course, to signify that a loop follows. In the parentheses we have the loop control variable,
x, which starts at zero (the first part, before the semicolon). The second part is what to stop at, in this case, 99, since
x cannot be greater than or equal to 100. The third part is the value to increment by every time the end of the loop iteration is reached, in this case our shortcut is used for
add 1 every time.
The while LoopThe
while loop. A loop to continue going around...and around, and around until a certain condition is reached. Let's take a look at the syntax for this one.
java
int x = 5;
while (x < 10)
{
System.out.println(x);
x++;
}
Well, not much to explain here, just put in the parentheses after
while whatever you want the condition to stop, to be.
The do-while LoopThe
do-
while. This is much the same as the
while loop, with only 1 difference. It
MUST execute at least once, as it doesn't know what the condition to stop is, until after it executes the code once.
java
int number = 10;
do
{
System.out.println(number);
number += 10;
}
while (number <= 100);
Well, there's one major difference between the
while line in the regular
while loop, and this one. Notice the semicolon, as this must be there for a
do-
while loop, as it signifies the end of the statement of the
do-
while loop. In other words, it just signifies the end.
_____________________________________________________________________
Modification Section:
The for each LoopNOTE: To use this loop you
must have JDK 1.5 or later, as that was when this loop was created.
Well, this is useful for traversing arrays in a different manner. It just goes for the entire length of the array, or ArrayList.
java
// our 'int' array, NUMBERS, is pre-defined
for (int number : NUMBERS)
System.out.println(number);
The basic syntax for this is
for (variable_to_use_inside_the_loop : array_to_look_in). It's the same as doing a
for (int x = 0; x < NUMBERS.length; x++).
_____________________________________________________________________
This has been my basic introduction to java looping. It's not a very in-depth tutorial, but it's not supposed to be. Then again, looping is a fairly routine and easy thing to accomplish.
Hope this helped!
This post has been edited by Locke37: 1 Aug, 2008 - 09:40 PM