Main Content

Does a for loop evaluate its end condition once, or on every iteration?

Archive - Originally posted on "The Horse's Mouth" - 2011-08-18 07:38:36 - Graham Ellis

All the languages that we teach have a for loop or the equivalent, which is a clean way of repeating a block of code with a rising or falling index number. It's used in many circumstances - for example in iterating through the months of the year (for m goes from 1 to 12) of in stepping through all the members of an ordered [list / array / table] *

In many cases, the end condition in this type of structure is evaluated before every iteration of the loop so that a changing end condition will be reflected immediatley. Look at this (Perl)

  $j = 8;
  for ($k=0; $k<$j; $k++) {
    print "Value $k\n";
    $j--;
    }


which runs like this:

  munchkin:laug11 grahamellis$ perl ph
  Value 0
  Value 1
  Value 2
  Value 3
  munchkin:laug11 grahamellis$


There's a similar structure / setup in PHP, Java, C and C++. See previous article [here] for a diagram and further example. And it applies to a Tcl for loop too - there's an example [here].

However, in some languages the loop terminator is evaluated once before the loop is entered, and no matter how the termination condition / value is changed while the loop is running, the for statement knows the iteration count from the start %. Here's a Ruby example:

  j = 8
  for i in 0..j
    puts "Value of loop variable is #{i}"
    j -= 1
  end


which runs like this:

  munchkin:laug11 grahamellis$ ruby rx
  Value of loop variable is 0
  Value of loop variable is 1
  Value of loop variable is 2
  Value of loop variable is 3
  Value of loop variable is 4
  Value of loop variable is 5
  Value of loop variable is 6
  Value of loop variable is 7
  Value of loop variable is 8
  munchkin:laug11 grahamellis$


In Lua, too, the loop count is evaluated once before the loop is entered, and that's the iteration count used. From this week's Lua course there's an example showing that - [here] and another [here].

In Python, too, the for and range / xrange construct is a single evaluation at the start. See an example of that [here].

* - Use "list", "array" or "table" depending on the language you're programming in - they are different words for a sequentially numerically indexed (ordere) collection.

% - In all languages, there is at least one mechanism such as break or last to exit prematurley. Rather more dramatically, return and exit will get you out of a loop and more besides.