Pages

Sunday, June 10, 2012

For loops


The for loops are used when the number of times you want the loop to be executed is previously defined. The for loop has a block of code which is executed every loop, and the conditional sentence to do the loops. The conditional sentence is divided is three parts: the initial value, the condition to stay in the loop and the action to do every loop. Each of those three fields are optional, but be carefull because you can convert it in an inifinitive loop.
The initial value is where you can create a variable and indicate its initial value. There, you can also use an existing value and set it to another value.
The condition to stay in the loop is set in the second field of the for loops. This indicate how many times will the code of the for loop be executed. The most common condition for this field is a counter, but any condition can be used. The parameters used here can be either modified int he third field or in the code of the for block. Basically, the condition waits for a true or false return.
The last field, is the action which execute the for loop at every loop. This action is most of the times incrementing a counter, but as I said before, it is an optional field, so the counter can be incremented inside the for loop. If the condition waits to the change of a parameter, then this field can be ommited.

Here is an example:
for(int i=0; i<4; i++){
System.out.println("numeber=" + i);
}

Output:
number=0
number=1
number=2
number=3

Another example:
int a = 0;
boolean exit = false;
for(;!exit;){
if (a == 4){
a++;
System.out.println("We still inside the loop");
}
else{
exit = true;
System.out.println("We are going out the loop");
}
}

Output:
We still inside the loop
We still inside the loop
We still inside the loop
We still inside the loop
We are going out the loop

The condition field can also be ommited, but in this case, we must do something to get out from the for loop. One instruction to get out of a loop, is simply a return instruction. In this case we go out of the for loop and the method. Another instruction is the break instruction. This instruction can be used to go out of any loop or a block of code (do-while, while, for, switch...).

No comments:

Post a Comment