The general structure of a basic for statement is:
for ( ForInit ; Expression ; ForUpdate ) Statement
ForInitis the initializer. It is run first to set up variables etc.Expressionis a boolean condition to check to see ifStatementshould be runStatementis the block of code to be run ifExpressionis trueForUpdateis run after theStatementto 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 = 0Expression=>i < 5ForUpdate=>i++Statement=>list [i] = i + 2;
Putting it together:
int i = 0;
while (i < 5) {
list[i] = i + 2;
i++;
}