M&C7: There is no best loop construct

The material on loops contains a number of examples for which we discussed more than one implementation. Some were based on different concepts while others were just different ways of doing the same task. While there are good and effective ways to write loops and there are clearly poor coding styles, every problem typically has a whole range of implementations that are good.  While established best practices should be followed, a number of elements of coding style is driven by personal preferences.

Consider Scratch programs 4, 5, and 6 in the Scratch section. All three programs perform the same task of a ball moving forever. While students may prefer one version over the other, each one is a well written program.

Consider Python programs 6 and 11 in the Loops in Python section which sum up the digits in an integer. We presented a Python program using a while loop (program 6) and one using a for-loop (program 11).  Both are correct solutions.

Example 12 in the Loops in Python section considered the problem of finding the greatest common divisor of two given integers. We presented two programs for determining the greatest common divisor of two given integers. One algorithm is based on Euclid’s algorithm and uses a while loop, the other one uses a for-loop trying all integers from 1 to b.  From a performance point of view, these two algorithms are very different and the for-loop one is rather inefficient.  Why?  Because the number of times the for-loop is executed runs from 1, 2, 3, to b-1, b. This is generally undesirable in programs.