For Loops
suggest changefor (int i = 0; i < 100; i++) {
System.out.println(i);
}
The three components of the for loop (separated by ;) are variable declaration/initialization (here int i = 0), the condition (here i < 100), and the increment statement (here i++). The initialization runs once, before the condition is tested. A variable declared there is in scope for the condition, the body, and the update, not for statements after the loop. Then the condition is checked. If it is true the body runs; if it is false the loop stops. After the body, the update runs and the condition is checked again.
The curly braces are optional when the body is a single statement. Braces are still worth using, because a later edit can attach the next line to the wrong statement.
The for loop components are optional. If your business logic contains one of these parts, you can omit the corresponding component from your for loop.
int i = obj.getLatestValue(); // i value is fetched from a method
for (; i < 100; i++) { // here initialization is not done
System.out.println(i);
}
The for (;;) { function-body } structure is equal to a while (true) loop.
Nested For Loops
A loop whose body contains another loop is a nested loop. A for loop in that position is a nested for loop.
for(;;){
//Outer Loop Statements
for(;;){
//Inner Loop Statements
}
//Outer Loop Statements
}
Nested for loop can be demonstrated to print triangle shaped numbers.
for(int i=9;i>0;i--){//Outer Loop
System.out.println();
for(int k=i;k>0;k--){//Inner Loop -1
System.out.print(" ");
}
for(int j=i;j<=9;j++){//Inner Loop -2
System.out.print(" "+j);
}
}