15 February 2011

"While" and "Do-While" Loops

I have started into a book that I picked up from the library entitled
Beautiful Code
published by O'Rielly Press. It's a compilation of top programmers thoughts on some of the most beautiful code that they have written and the logic and theory behind it. I was slightly apprehensive that it would be way over my head, having no formal training in the field. I'm understanding about 75 - 85% of the discussion so far. What is really insightful, however, are the explanations as to why and what makes their code samples so effective. Hopefully by the end I'll be thinking just a bit more like a programmer.

Today's reading has me thinking about "Do-While" loops, as there was one implemented in the code that I was studying. I'm studying them out in PHP as that is the language that I work in. The online PHP manual has been very helpful in providing some effective examples.

There is one key difference between "Do-While" loops and "While" that I have observed. Both loops have a true/false statement to determine whether the loop is to be processed. The distinction between the two is that in a normal "While" loop that check is performed at the beginning of the loop. This makes is so that the first time the statement is checked the return value must be true or else the while loop will not be executed.

On the contrary, with a "Do-While" loop,  all scripts inside the loop are executed  at least once before the statement is checked. I hope to experiment with this a little more and then report back on how I've found this variation to be helpful.

This example illustrates a quick way of executing a "Do-While" loop without curly brackets.

0 comments:

Email Marketing