How do I convert this for loop into a while loop?

The general structure of a basic for statement is:

for ( ForInit ; Expression ; ForUpdate ) Statement
  • ForInit is the initializer. It is run first to set up variables etc.
  • Expression is a boolean condition to check to see if Statement should be run
  • Statement is the block of code to be run if Expression is true
  • ForUpdate is run after the Statement to e.g. update variables as necessary

After ForUpdate has been run, Expression is evaluated again. If it is still true, Statement is executed again, then ForUpdate; repeat this until Expression is false.

You can restructure this as a while loop as follows:

ForInit;
while (Expression) {
  Statement;
  ForUpdate;
}

In order to apply this pattern to a “real” for loop, just substitute your blocks as described above.

For your example above:

  • ForInit => int i = 0
  • Expression => i < 5
  • ForUpdate => i++
  • Statement => list [i] = i + 2;

Putting it together:

int i = 0;
while (i < 5) {
  list[i] = i + 2;
  i++;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)