Introduction
The purpose of loop statements is to repeat Java statements (blocks of code) many times. There are several kinds of loop statements in Java.
The While Loop
The while statement is used to repeat a block of statements while some condition is true. The condition must become false somewhere in the loop, otherwise it will never end. Here is an example:
int i = 1;
while (i <= 20) {
System.out.println(i);
i++;
}
The for loop
Many loops consist of three operations surrounding the body: (1) initialization of a variable, (2) testing a condition, and (3) updating a value before the next iteration. The for loop groups these three common parts together into one statement, making it more readable and less error-prone than the equivalent while loop. For repeating code a known number of times, the for loop is the right choice.
The following for loop is exactly the same as the while loop above:
for (int i = 1; i <=20; i++){
System.out.println(i);
} //end of loop
The for statement is broken up as follows (note the ";" between each part):
for ((1) initialization of a variable; (2) testing a condition; (3) updating the value of the variable before the next iteration)
Lets look at some nested loop examples:
for (int rows = 0; rows <=5; rows ++){
for (int star = 0; star < rows; star ++){
System.out.print("*");
}
System.out.println();
}
The above nested loops should print the following output to the console:
*
**
***
****
Now lets look at another nested loop example, this time using a while loop:
for (int i = 1; i <=20; i = i + 1){
System.out.println(i + ":");
int y = 0;
while (y <= i){
System.out.print(" "+ y+" ");
y++;
}
}
The above example, should print out a slew of numbers that looks something like this:
1:
0 1
2:
0 1 2
...... and so on!
The above are the two most commonly used loops in Java, and should get you through most of your looping needs. There are, however, two other types of loop in java. The more advanced "foreach" loop (no need to worry about that till next year!) and the "do..while" loop which I'll leave to your own research (unless someone else wants to contribute here!)