How a for loop works Java, Perl and other languages
Archive - Originally posted on "The Horse's Mouth" - 2011-03-12 19:46:56 - Graham Ellis
Java, Perl, PHP, Ruby, C, C++, Tcl and many other languages support a "for" loop construct.
When your program enters the top of the loop, it performs the first statement in the brackets ... in this Perl example, that's to initialise the $now variable to 1. It then evaluates the expression given as the second element in the brackets - in the example checking if $now is less that or equal to 12. If that's true, the block is performed; if it's false, the program carries on running after the block.
If the block is performed (it doesn't have to be - a for loop's block may run zero times!), the third and final statement in the initial brackets is performed after the block - that adds one to $now in the example - and then the test in the second item (the expression) is performed again. And again, if that's true, the block is performed; if it's false, the program carries on running after the block.
You COULD do without a for loop ... move the first statement in the brackets above the loop code, change for to while and move the last statement inside the block as its very last statement. But that makes for three statements rather than one ... and code that's going to much harder to follow if you have to come back and update it later.
They say "imitation is the sincerest form of flattery" ... so I'm flattered by Martin Naughon's web site ([here]) which uses my diagram to illustrate the for loop. Actually, my feeling flattered also left me feeling slightly peeved initially because I've not been asked for permission, but that has now been sorted out between us. And - talk about mixed emotion - I'm open-mouthed at Martin's text which - reads "A lot of people do not know exactly how the for loop works in Java or Perl but they know how to make it work for them. Developers usually make it work through trial and error. The picture below illustrates exactly how a for loop works with arrows. If you know this picture, it will help you with some questions in the Sun Certified Java Programmer exam.". Martin - I hadn't realised how poorly informed most programmers were, nor how trivial the questions are in the Java Certification exams; actually, I think you're wrong in your view of the knowledge of most of our fellow programmers.
We cover the for loop on all of our programming courses - see [here].
Note - the for loop in Python does NOT work in the way described above - there's a commented example [here] stepping up through a range, and another Python example [here] that iterates through a list.