Do-While Loops
Do-While loops work almost exactly like While loops. Code inside a do-while loop will run once first, then check to see if the condition is met.
Example 1:
Compare the results of this program using a While Loop vs a Do-While Loop:
While Loop:
x = 1;
while(x > 5)
{
System.out.println("Looping");
x = x + 1;
}
System.out.println("Done");
Do While Loop:
x = 1;
do
{
System.out.println("Looping");
x = x + 1;
} while ( x > 5 );
System.out.println("Done");
For Loops
For Loops allow you to easily write code that loops a specific number of times
Compare the output of the following two loops:
While Loop:
x = 1;
System.out.println("Start");
while (x < 4)
{
System.out.println(x);
x = x + 1;
}
System.out.println("End");
For Loop:
System.out.println("Start");
for (x = 1; x < 4; x = x + 1)
{
System.out.println(x);
}
System.out.println("End");