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.
Some other articles
Y104 - Lists and Tuples Embedding more complex code into a named block Shuffling a list - Ruby and Python Collections in Python - list tuple dict and string. Spike solutions and refactoring - a Python example Stepping through a list (or an array) in reverse order List slices in Python - 2 and 3 values forms, with an uplifting example All possible combinations from a list (Python) or array (Ruby) Beware - a=a+b and a+=b are different - Python Arrays of arrays - or 2D arrays. How to program tables. Copying - duplicating data, or just adding a name? Perl and Python compared Traffic lights in Python Python - fresh examples of all the fundamentals Strings as collections in Python Creating and iterating through Python lists Looking for a value in a list - Python Tektronix 4010 series / Python Tuples This article Python collections - mutable and imutable Python - extend v append on a list The ternary operator in Python Overloading of operators on standard objects in Python 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 Does a for loop evaluate its end condition once, or on every iteration? 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 This article 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 P206 - More Loops and Conditionals While, for, foreach or something else to loop. Ruby v Perl - a comparison example Perl - making best use of the flexibility, but also using good coding standards How a for loop works Java, Perl and other languages Some more advanced Perl examples from a recent course Multiway branches in Perl - the given and when syntax Alternative loops and conditionals in Ruby and Perl Are you learning Perl? Some more examples for you! A pint of Black Rat, and a lazy barman Setting a safety net or fallback value in Perl switch and case, or given and when in Perl For loop - checked once, or evety time? Ruby v Perl comparison and contrast Question Mark - Colon operator (Perl and PHP) Saying NOT in Perl, PHP, Python, Lua ... Ruby, C, Java and more - getting out of loops This article Smart English Output - via PHP and Perl ? : operator Breaking a loop - Ruby and other languages The ternary operator in Python What - no switch or case statement? Perl - redo and last without a loop 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) Does a for loop evaluate its end condition once, or on every iteration? 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 This article 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 Does a for loop evaluate its end condition once, or on every iteration? 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? This article 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) Does a for loop evaluate its end condition once, or on every iteration? 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 This article Smart English Output - via PHP and Perl ? : operator Breaking a loop - Ruby and other languages Wimbledon Neck