2.8.3 - For Loops

The for loops are a shortcut to while loops. In the for loops the loop control is realised at the beginning of the loop. The structure of the forloops is as follows :

```for {initialisation;termination;incrementation}
body of the loop
}
```

Initialisation step is executed only once in the beginning of the loop. The loop counter is initialised in this step. The loop counter may also be declared here, this is a convenience but we should take into account that the lifespan of the variable is limited in the definition block which the variable is declared. If we wil need the value of the loop counter outside of the loop block, it should be declared outside of the for block.

Termination step is the normal loop sentinel, a boolean expression exactly the same as the while loops. It is evaluated in every iteration in order to decide the continuation of the loop.

Incrementation step is evaluated in each iterationand the loop counter is incremented or decremented.

The for loops are very flexible but they are only a avariant of the while loops. They are especially useful when a preset value of iterations is known. One example of the for loops are given below:

2.8.3 image - 1 : for loop

It is not surprising that for the same problem, the flowchart of while and for loops are the same. They are the same loop after all, it is normal that they share the same flowchart. But, the program structure is quite different and for loops are more easy to apply.

```package preliminary;

public class ForLoop {

public static void main(String[] args){
int sum = 0;
for( int i = 0 ; i < 101 ; i++) {
sum = sum + i;
} // end for
System.out.println("The Sum Of The First 100 integers is :  " + sum);
} // end main

} //end class ForLoop

```
```The Sum Of The First 100 integers is :  5050
```

Looking to the program, loop sentinel is checked now for one plus the target value, because the loop counter is incremented after updating the sum, that is before leaving the actual iteration.

We can use break and continue as usual with for loops.

2.8.4 - For-Each Loops

For-Each loops are used with object to scan trough all the profery of an object. We will cover them when we are studying object oriented programming (OOP).