You are on page 1of 2

PROG2 - Discussion Forum Unit 2 – Alexandre Goncalves Pinheiro

The differences between FOR, WHILE and DO WHILE


FOR: The condition is tested before entering the loop, you can set/increment/decrement the auxiliary variable along
with the condition.
WHILE: The condition is tested before entering the loop, but the auxiliary variable is set before the loop and
incremented/decremented inside the loop.
DO WHILE: The same of the WHILE loop, but the condition is tested after the first loop, that will be run anyway.

// Do_While_For.java
public class Do_While_For{
  public static void main(String[] args) {
System.out.println("########  PART 1  ########");
int i = 0;
System.out.print("While 1---------------");
while (i < 5) {  // Condition is tested before entering the loop
  System.out.print(" "+i);
  i++; 
}

System.out.println();
i=0;
System.out.print("Do_While 1---------------");
do {
  System.out.print(" "+i);
  i++; 
} while (i < 5); // Condition is tested after entered the loop

System.out.println();
System.out.print("For 1---------------");
for (int i2 = 0; i2 < 5; i2++) { // Condition is tested before entering the loop
  System.out.print(" "+i2);
}
System.out.println("\n\n");
System.out.println("########  PART 2  ########");
i=0;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.print("Do_While 2---------------");
do {
  System.out.print(" "+cars[i]);
  i++; 
} while (i < 4);
System.out.println();
i=0;
System.out.print("While 2---------------");
while (i < 4) {
  System.out.print(" "+cars[i]);
  i++; 

System.out.println();
System.out.print("For 2---------------");
for (int i2 = 0; i2 < 4; i2++) {
  System.out.print(" "+cars[i2]);
}

System.out.println("\n\n");
System.out.println("########  PART 3  ########");
System.out.print("For 3---------------");
for (int i2=0; i2<4 ; i2++) System.out.print("@");
System.out.println();
i=0;
System.out.print("While 3---------------");
while (i < 4) {
  System.out.print("#");
  i++; 

System.out.println();
System.out.print("Do_While 3---------------");
i=0;
do {
  System.out.print("$");
  i++; 
} while (i < 4);

} }

OUTPUT:

Reference:
Eck, D. J. (2019). Introduction to programming using Java, version 8.1. Hobart and William Smith College.
http://math.hws.edu/javanotes.

You might also like