The Trick Of The Mind - Advanced Loops |
Written by Mike James | ||||
Monday, 12 February 2024 | ||||
Page 1 of 3 Loops are a fundamental part of programming and they go deep. This is an extract from my book Trick of the Mind which explores what it is to be a programmer. The Trick Of The Mind - Programming & ComputationalThoughtBuy Now From Amazon Chapter List
<ASIN:1871962722> <ASIN:B09MDL5J1S> In the chapter but not in this extract
Enumeration LoopsEnumeration loops simply repeat code a specified number of times. In many languages, Logo for example, you can write things like: Repeat 10 instruction1 instruction2 instruction3 End Repeat and this means repeat the code block ten times. Of course, this can be written as a conditional loop with the help of a counter: count = 1 Do While count <=10 instruction1 instruction2 instruction3 count = count+1 Loop This looks complicated and it is a bit messy, but enumeration loops often repeat code that need to make use of a counter or index. The counter in this case starts at 1 and finishes at 10. Enumeration loops are often used to process arrays and other indexed data structures and in these cases a counter is used as the index. The big problem with implementing enumeration loops as conditional loops is that the process is error-prone. You just want a loop that is obeyed 10 times with a counter that runs from 1 to 10 but getting the condition to end the loop correctly depends on where the counter update occurs in the loop. You might end up with a loop that runs from 0 to 9, 1 to 10 or 1 to 11 and so on. This is the reason why enumeration loops are most often implemented as some sort of For loop which clearly specifies the behavior of the counter or index. For example: For i=1 To 10 instruction1 instruction2 instruction3 Next i will repeat the code block for values of i from 1 to 10 inclusive. In many ways this "explicit index bounds" form of the For loop is about as good as it gets. It is a suitable abstraction of the indexed enumeration loop idea. It is easy to see that this fits in with doing something to an array. For example: For i=1 To 10 do something with A[i] Next i One subtlety of enumeration loops is whether they are While or Until style enumeration loops? That is, can the body of the loop be skipped completely? In most cases the answer is “yes”, but you need to find out in the language of your choice what happens in the case of For loops like: For i=1 To 0 Does the loop execute zero times or once? The sad news is that languages are not always as clear about enumeration as they should be. |
||||
Last Updated ( Tuesday, 13 February 2024 ) |