     Next: while () {} Up: Loops Previous: Variable scoping   Contents   Index

## General for ( ) { }

The general form of a for loop is as follows:
```  for (initialization_statement; continuation_condition; iteration_command) {
statement_1;
statement_2;
...
}
```
In this,
• initialization_statement is the statement to execute when the loop is first entered;
• continuation_condition is the condition that must be satisfied in order that the next iteration take place;
• iteration_command is the command to be executed each time through the loop;
As an example, here is a way to loop over all indices in an array, and subsequently print out the array elements corresponding to that index:
```  my @arr = (4, 1, 8);
for(my \$i=0; \$i<=\$#arr; \$i=\$i+1) {
print qq{\\$arr[\$i] has value \$arr[\$i]\n};
}
```
Note the use of the assignment
```  \$i = \$i + 1;
```
in the for loop. Mathematically, this statement doesn't make sense, but in computer programming, it is a powerful concept - it means to assign a new value of \$i to the old value of \$i plus 1. Because this arises so often there is a shorthand available:
```  \$i += 1;   # add 1 to the current value
\$i -= 1;   # subtract 1 from the current value
\$i *= 1;   # multiply the current value by 1
\$i /= 1;   # divide the current value by 1
```
Also, because adding (and subtracting) one from the current value is so common, these particular operations are given a further shortcut:
```  \$i++;    # increase \$i by 1
\$i--;    # decrease \$i by 1
```

It is important to recognize at what point in a for loop the various operations take place. When the loop is first entered, the initialization statement is executed, and the truthfulness of the continuation statement evaluated. If it's true, the block of statements between the curly braces are run through. The iteration command is then executed, and the truthfulness of the continuation condition evaluated. If true, the statements between the curly braces are executed again. This loop continues until the continuation condition is no longer satisfied, upon which the loop is terminated.     Next: while () {} Up: Loops Previous: Variable scoping   Contents   Index