The Trick Of The Mind - The Loop Zoo |
Written by Mike James | |||||||
Monday, 03 April 2023 | |||||||
Page 3 of 3
Fractional LoopsWhat about loops with exit points somewhere other than the start or the end of the loop? What is so wrong with them? For example: Do In this case instruction1 will be executed one or more times, but instruction2 will be executed zero or more times. In fact the difference between instruction1 and instruction2 is even more pronounced. Instruction1 will always be repeated once more than instruction2. This is a bit like repeating the code so many and a half times. This is often thought to be unnecessarily complicated and having exit points anywhere other than at the start or the end is frowned upon. In fact, structured language enforced this by only providing the While and Until loop and no other way to break out of a loop early. Recently languages have included a break or exit statement that does allow the placing of an exit point anywhere you like. They should be used sparingly and only when they make the intent clearer. The ContinueNow we come to a fairly recent innovation in loops – the Continue statement. The logic seems to be that if a language introduces a Break statement that terminates a loop why not have a statement that continues a loop? That is: Do While condition1 instruction1 If condition2 Then Continue Do instruction2 Loop In this case the loop ends when condition1 is false. What the Continue statement does is skip instruction2 if condition2 is true. That is, the Continue statement seems to transfer control to the end of the loop and starts another repeat. A few moments thought should make clear that this is just: Do While condition1 instruction1 If Not condition2 Then instruction2 Loop The Continue statement doesn't have much to do with the structure of loops. It is really just a shorthand for an If statement that skips a block of code. You can argue that Continue and Break are covert ways of sneaking Goto back into programming languages. In book but not in this extract
Summary
The Trick Of The Mind - Programming & ComputationalThoughtBuy Now From Amazon Chapter List
<ASIN:1871962722> <ASIN:B09MDL5J1S> To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
|||||||
Last Updated ( Tuesday, 04 April 2023 ) |