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.
Some other articles
Y103 - Conditionals and Loops Conditional operators in Python Equality (in Python) Method, Class, Module, Package - how to they relate in Python? Setting up and tearing down with the Python with keyword Finding sum, minimum, maximum and average in Python (and Ruby) Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) If elif elif elif - multiway selection in Python Identity in Python Flowchart to program - learning to program with Well House Learning to program - the if statement. Python. Finding the total, average, minimum and maximum in a program Python or Lua - which should I use / learn? Python for loops - applying a temporary second name to the same object This article How a for loop works Java, Perl and other languages Python - fresh examples from recent courses Groupsave tickets - 3 or 4 train tickets for the price of 2 Learning to program in Python 2 ... and / or in Python 3 Saying NOT in Perl, PHP, Python, Lua ... Equality, sameness and identity - Python Decisions - small ones, or big ones? No switch in Python Python is like a narrowboat Python - when to use the in operator New - Conditional expressions in Python 2.5 Python - block insets help with documentation The ternary operator in Python Wimbledon Neck What - no switch or case statement? U103 - Conditionals and loops repeat until in Lua - a one or more rather than a zero or more loop Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) Lazy operators in Lua - what they mean, and examples The goto statement in Lua Python or Lua - which should I use / learn? This article Lua examples - coroutines, error handling, objects, etc For loops in Lua Ternary operators alternatives - Perl and Lua lazy operators Clean code, jump free (Example in Lua) Saying NOT in Perl, PHP, Python, Lua ... Short circuit evaluation (lazy operator) in Lua T203 - Conditionals and Loops Working out distance between places, using OS grid references and a program in Tcl Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) Comparing loop commands in Tcl Trapping errors in Tcl - the safety net that catch provides This article Tcl - the danger of square brackets in a while command Tcl - a great engineering language A short form of if ... then ... else Tcl - nice and nasty Saying NOT in Perl, PHP, Python, Lua ... Decisions - small ones, or big ones? Tcl - using [] or {} for conditions in an if (and while) Joining lists in Tcl. Indirect variables in Tcl. R104 - Control Structures Alternating valuses / flip-flop / toggle - example in Ruby Where does Ruby load modules from, and how to load from current directory Separating your code for easier testing, understanding and re-use; example in Ruby Finding sum, minimum, maximum and average in Python (and Ruby) Conditionals, loops and methods in Ruby - a primer with simple examples Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) Muttable v immutable and implications - Ruby Finding the total, average, minimum and maximum in a program Ruby v Perl - a comparison example Assigning values to variables within other statements - Ruby This article Multiple inputs, multiple out, ruby functions Is this number between? Does this list include? - Ruby How a for loop works Java, Perl and other languages Returning multiple values from a function call in various languages - a comparison Ruby training - some fresh examples for string handling applications Splitting data reading code from data processing code - Ruby Why do I need brackets in Ruby ... or Perl, Python, C or Java Alternative loops and conditionals in Ruby and Perl For loop - checked once, or evety time? Ruby v Perl comparison and contrast Passing code to procedures and yield in Ruby A short form of if ... then ... else Learning to program in Ruby - examples of the programming basics Ruby, Perl, Linux, MySQL - some training notes Ruby to access web services Ruby Programming Course - Saturday and Sunday What to do with a huge crop of apples Clean code, jump free (Example in Lua) Saying NOT in Perl, PHP, Python, Lua ... Some Ruby programming examples from our course Ruby, C, Java and more - getting out of loops for loop - how it works (Perl, PHP, Java, C, etc) A better alternative to cutting and pasting code Ruby's case - no break Equality in Ruby - == eql? and equal? Breaking a loop - Ruby and other languages 1st, 2nd, 3rd revisited in Ruby P204 - Conditionals and Loops Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) Showing what programming errors look like - web site pitfall Flowchart to program - learning to program with Well House This article Increment operators for counting - Perl, PHP, C and others Are you learning Perl? Some more examples for you! For loop - checked once, or evety time? Ruby v Perl comparison and contrast Do not copy and paste code - there are much better ways Ternary operators alternatives - Perl and Lua lazy operators Equality and looks like tests - Perl Saying NOT in Perl, PHP, Python, Lua ... Learning to program in Perl Decisions - small ones, or big ones? Lexical v Arithemetic testing, Bash and Perl Smart English Output - via PHP and Perl ? : operator -> , >= and => in Perl Wimbledon Neck J704 - Loops and Conditional Statements Java example - for loop and conditionals from course exercise A behaviour driven example of writing a Java program Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) This article How a for loop works Java, Perl and other languages Setting up individual variables, and arrays, in Java - some commented examples for and foreach in Java Saying NOT in Perl, PHP, Python, Lua ... Ruby, C, Java and more - getting out of loops for loop - how it works (Perl, PHP, Java, C, etc) Wimbledon Neck H104 - Control Statements Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) While, for, foreach or something else to loop. Flowchart to program - learning to program with Well House This article How a for loop works Java, Perl and other languages Predictions for the seagull population Extracting real data from an exported file in PHP or Perl Question Mark - Colon operator (Perl and PHP) Saying NOT in Perl, PHP, Python, Lua ... Decisions - small ones, or big ones? for loop - how it works (Perl, PHP, Java, C, etc) Testing for one of a list of values. Smart English Output - via PHP and Perl ? : operator Breaking a loop - Ruby and other languages Double and Triple equals operator in PHP The ternary operator in Python Don't repeat code - use loops or functions Assignment, equality and identity in PHP Wimbledon Neck Code and code maintainance efficiency C203 - Conditionals and Loops Learning to program sample program - past its prime, but still useful Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) This article Loops - a comparison of goto, while and for Breaking the running sequence - an introduction to conditional statements and loops How a for loop works Java, Perl and other languages New year, new C Course Increment operators for counting - Perl, PHP, C and others Function Prototypes in C New C Examples - pointers, realloc, structs and more Saying NOT in Perl, PHP, Python, Lua ... Ruby, C, Java and more - getting out of loops for loop - how it works (Perl, PHP, Java, C, etc) Smart English Output - via PHP and Perl ? : operator Breaking a loop - Ruby and other languages Wimbledon Neck