When writing a program, you'll often want to repeat a block of code, counting up through a table or performing a block of code with an input value (loop counter) that goes up 1, 2, 3, 4 etc.
You COULD do this using a
while loop, but this means you have to specify each of
• how to start (initialise) the loop counter
• how to test the loop counter to see if it's completed
• how to alter the loop counter each time round
and to do each of these separately means that the maintainer of the code is going to have to look in three places at once to work out what's going on.
Most languages have a
for loop construct which pulls all three elements into one statement, for example:
for ($k=0; $k<25; $k++) {
which means START at zero, REPEAT the loop while $k is less that 25 and before EACH SUBSEQUENT test and loop add 1 to $k.
Here's a diagram to show how that works
The GREEN shows the initial entry to the loop, where the initial value is set and then the condition is tested.
The ORANGE shows each subsequent time round the loop, where the last clause (the increment) is performed before the condition is retested
and the RED shows how the loop exits once the condition has gone false. You'll note that a for loop CAN exit straight away, since the test is done on entry as well as each time the last clause has been run.
(written 2007-06-06 10:02:57)
Associated topics are indexed under
C203 - C and C based languages - Conditionals and LoopsH104 - PHP - Control StatementsJ704 - Java - Loops and Conditional StatementsP206 - Perl - More Loops and ConditionalsR104 - Ruby - Control StructuresY104 - Python - Lists and Tuples
Some other Articles
Object Relation Mapping (ORM)Asda opening large new store in MelkshamPerl, the substitute operator sBathtubs and pecking birdsfor loop - how it works (Perl, PHP, Java, C, etc)Judging the quality of contributed Perl codeSunday afternoonWhat are factory and singleton classes?Five of the best - pictures from LondonAn update on Perl - where is it going?