Monday, September 29, 2008

The For Loop


The for loop.

Its format is: for (initialization; condition; increase) statement; and its main function is to repeat statement while condition remains true, like the while loop. But in addition, for provides places to specify an initialization instruction and an increase instruction. So this loop is specially designed to perform a repetitive action with a counter.

The initialization and increase fields are optional. They can be avoided but not the semicolon signs among them. For example we could write: for (;n<10;) if we want to specify no initialization and no increase; or for (;n<10;n++) if we want to include an increase field but not an initialization.

Optionally, using the comma operator (,) we can specify more than one instruction in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an instruction separator, it serves to separate more than one instruction where only one instruction is generally expected. For example, suppose that we wanted to intialize more than one variable in our loop:

for ( n=0, i=100 ; n!=i ; n++, i-- )

{

// whatever here...

}

This loop will execute 50 times if neither n nor i are modified within the loop:

n starts with 0 and i with 100, the condition is (n!=i) (that n be not equal to i). Beacuse n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50.

Source: cplusplus.com


No comments: