From LQWiki
Jump to: navigation, search

For Loop

For example, in BASIC, one can write:

For i=1 to 10
print i
Next i

To list the values of i from 1 to 10. i is said to be a loop parameter, as the code within the loop can examine the value of i to determine the position within the loop.

C-Style for Loop Instruction

One of the oddities of the C language, which has been inherited by other languages like C++ and Java, is the use of the keyword for to implement a (possibly) unbounded loop.

The C language syntax is:

for (init1[,init2,[…]];cond;chg1[,chg2,[…]]) {

Here, init1, init2, and so on, are all intended to be used to initialize loop parameters. However, they can be any instructions executed only at the start of the first iteration of the loop. cond is the exit condition. chg1, chg2, and so on, are supposed to be used to set loop parameters for the next iteration of the loop. However, any instructions can be used, and will be executed at the end of each iteration.

Linux Shell Scrips

The BASH language supports a C-style for loop construct:

for (( cmd1; cmd2; cmd3 )) ;
 do cmd4;

The effect of this construct is to execute cmd1, followed by cmd2, then cmd4, then cmd3. The execution of cmd2 through cmd3 is repeated until cmd2 evaluates to zero.

It is normal to omit several of the various parts; if the exit condition cmd2 is omitted then the loop does not terminate.