Index

chapter1

chapter2page1

chapter2page2

chapter2page3

chapter2page4

chapter2page5

chapter2page6

chapter2page7

chapter2page8

chapter2page9

chapter2page10

chapter2page11

chapter2page12

chapter2page13

chapter2page14

chapter2page15

chapter2page16

chapter2page17

chapter2page18

chapter2page19

chapter2page20

chapter2page21

chapter2page22

chapter2page23

chapter2page24

chapter2page25

chapter2page26

chapter2page27

chapter2page28

chapter2page29

chapter2page30

chapter2page31

chapter2page32

chapter2page33

chapter2page34

chapter3

link one

link one

link one

link one

link one

link one

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:

for loop flowchart

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).

<< Index

Polyglott HTML5(XHTML5 compliant HTML5 code)