Pages

4.01.2014

Two loops you didn't know about

Most of us that program are familiar with a few basic types of loops.  We all know the while loop, the for loop, the "for each" loop and the "do while" loop.   Today you'll learn about two little used loops that are built into many modern languages.  I'll show you the pseudo code for the constructs.

Everybody has written some sort of program that got stuck in an infinite loop.  More than likely you wrote a while loop where the condition never became false.  It's possible to write and infinite "for each" loop, but it just takes more work. If you find yourself needing an infinite "for each" loop, you could instead use the special "for ever" loop construct.  This loop is especially handy when you want to iterate through a list infinitely.  The forever loop will iterate through your collection and start right over at the beginning.

forever ( theList : listItem ) {
    //do some stuff
}

The next obscure loop is similar to a "do while" loop.  The do while loop executes the body of the loop once, evaluates the conditional, and executes the body again until the condition is false.  The "don't while" loop is slightly different.  The don't while loop skips over the body of the loop and evaluates the condition.  If the condition is true, the body of the loop is skipped, until the condition becomes false at which point the loop body executes exactly once.

don't{

      //only executes once
     // after the condition is false

}while(condition)

Next time you're trying to write obscure barely functional code, consider using these special loops.  These loops are a really convenient way to confuse new programmers that look at your code.  Experienced programmers will be equally baffled by your decision to utilize such loops.  Happy April 1st!