Java: Loops
While Loops
While loops will loop something over while a certain condition is true.
For example:
int VarOne = 0;
int VarTwo = 10;
while(VarOne < VarTwo){
System.out.println(VarOne);
VarOne++;
}
When executed this should display the numbers 0 - 9 (if you incremented before displaying it would be 1-10).
You should understand most of this code (through logic), the only bit you might not understand is "VarOne++;".
This is called incrementing, all it does is add one to VarOne.
As for the while loop itself, you can put all sorts of conditional statements in there.
Do While loop
The do while loop is exactly the same as the while loop apart from the statements inside the while loop will run at least once.
For example:
int VarOne = 0;
int VarTwo = 10;
do{
System.out.println(VarOne);
}while(VarOne == VarTwo);Although the while condition is not true, it will still output VarOne once before checking the condition and then stopping.
For Loop
For loops are the most common loops, they are really easy to use, and useful.
The first part of the for loop is the initialisation, the second is the condition, and the third is the action.
Ill leave you to figure the rest out:
int VarOne = 0;
for(int VarTwo = 10; VarOne < VarTwo; VarOne++){
System.out.println(VarOne);
}
As you can see these are basically a better version of while loops. They are easier to use, take up less space etc..
Like the while loop this would output the numbers 0 - 9.
Back to Java

