Main Content

for loop - how it works (Perl, PHP, Java, C, etc)

Archive - Originally posted on "The Horse's Mouth" - 2007-06-06 10:02:57 - Graham Ellis

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.