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 ifStatement
should be runStatement
is the block of code to be run ifExpression
is trueForUpdate
is run after theStatement
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++;
}