For Loop While Loop Conversion

Converting a WHILE loop to a FOR loop may not be that straightforward, but converting a FOR loop to a WHILE loop is always easy.

First, let's have a comparison of the structures of FOR loop and WHILE loop:

FOR Loop Structure:

for(Initialization; Condition; Update)
{
   Statements //inside the loop body
}
//statements after for loop

WHILE Loop Structure:

while (Condition)
{
   Statements; //inside the loop block/body
}

We can see that both FOR loop and WHILE loop have Condition inside the (). but FOR loop has two more items, Initialisation and Update. Where to place it in WHILE loop?

According to the post on FOR loop,

  • The initialization statement is executed only once before the loop starts, so we place it before the WHILE loop
  • The update statement is executed after the loop body is executed, so we place it at the end of the WHILE loop body
Initialisation; //from the FOR loop
while (Condition)
{
   Statements; //inside the loop block/body
   Update; //from the FOR loop
}

That's it!

Example:

for (int i = 0; i < 8; i++) {
   System.out.println(i);
}
System.out.println("done");

WHILE Loop version:

int i = 0; //initialisation
while (i < 8) {
   System.out.println(i);
   i++; //update
}
System.out.println("done");
Last modified: Wednesday, 31 October 2018, 6:09 PM