- Rerun certain part of code until a condition fails.
- Can be achived by using for or while statements.
- A for structure has three parts: init, test, and update. Each part must be separated by a semi-colon ";".
- The loop continues until the test evaluates to false.
for (init; test; update) {
statements
}
int points_to_draw = 5;
int startX=10;
int startY=10;
for(int i=0; i < points_to_draw; i++){
point(i*startX,i*startX);
}
- The while structure executes a series of statements continuously while the expression is true.
while (expression) {
statements
}
int points_to_draw = 5;
int startX=10;
int startY=10;
while ( points_to_draw > 0) {
point( points_to_draw*startX, points_to_draw*startY);
points_to_draw = points_to_draw -1;
}
- Use
break;
to end the execution of a structure such as switch(), for(), or while() and jump to the next statement after that.
int points_to_draw = 5;
int startX=10;
int startY=10;
while (true) {
if(points_to_draw == 0){
break;
}
point( points_to_draw*startX, points_to_draw*startY);
points_to_draw = points_to_draw -1;
}
- Use
continue; to skip the reminder of the block and jump to next iteration. Use inside of a for() or while().
//dont draw point no 3
int points_to_draw = 5;
int startX=10;
int startY=10;
while ( points_to_draw > 0) {
if(points_to_draw == 3){
continue;
}
point( points_to_draw*startX, points_to_draw*startY);
points_to_draw = points_to_draw -1;
}