Share
Share
 

Do While vs While

By Chris London

When I started programming I only learned about do ... while statements and I didn’t know about while statements. There are some times when my code would’ve been a lot cleaner if I had known about while statements. To save you all the trouble of what I had to go through I’m writing this post. For those of you who already know the difference between while and do ... while I have included a little-known trick that may interest you. Just skip on down to the bottom.

The code is in PHP but a lot of the syntax is very similar in most other programming languages. There really aren’t many ways to syntax a while statement so I’m sure there won’t be much of an issue with other languages. If you need a specific example for a specific language you can post a comment and I’ll give you one.

While Statement

While statements are efficient loops that will continue to loop until the condition is false. Here is the syntax:

while (condition) {
     // loop code here
}

The condition can be whatever you want. As long as the condition is true it will continue to loop. Here is an example in PHP:

// get current time
$start_time = time();
// set counter to zero
$counter = 0;
 
// count for 10 seconds
// while the current time minus start time is less than 10 seconds
while (time() - $start_time < 10) {
     // count once
     $counter++;
}
 
// display our results
echo 'I counted to ' . $counter . ' in 10 seconds!';
// I counted to 29964475 in 10 seconds!

Your computer/server will most likely produce a different number since everyone’s computer processing speed is different. You will even get a different number each time you run it because of server load and other factors.

BE CAREFUL – While loops can create an infinite loop. Infinite loops are BAD. Computers are stupid and can’t tell if they’re stuck in an infinite loop. Thank goodness that PHP has a time out limit (I hope you haven’t turned off the time limit or extended it too much). Here is a basic example:

while (1 == 1) {
     // loop code here
}

Since 1 will always equal 1 the computer will keep looping forever. However, if you know what you’re doing while (1 == 1) or while (true) can actually be useful. This is where break comes into play. We discuss break and continue in a little bit.

Do … While Statement

Do ... While statements are also efficient loops that will continue to loop until the condition is false. They are identical to while statements except that it starts with do and the while condition comes after the braces. Here is the syntax:

do {
     // loop code here
} while (condition);

The Difference

The difference between a while loop and a do ... while loop is that in a while loop the condition is checked before the first iteration of the loop and in a do ... while the condition is checked. Here is a quick example, obviously 1 does not equal 2 so the condition is false:

while (1 == 2) {
     // this code will never run
}
 
do {
     // this code will run once
} while (1 == 2);

How NOT To Use A While Statement

I hope none of you have ever done this. I guess it’s possible that this might slip into someone’s code if they don’t know what a for loop is.

The wrong way:

$counter = 0;
while ($counter < 10) {
     // loop code here
     $counter++;
}

The right way:

for ($i = 0; $i < 10; $i++) {
     // loop code here
}

Break and Continue

Break is a cool statement that tells the computer to end a loop. This works not only in while and do ... while loops but also for loops and switch statements. So for example if Joe is asleep and Fred is trying to wake up Joe we can end the loop if Fred gives up:

//this code is theoretical since these functions don't exist
while (joe_is_asleep()) {
     try_to_wake_up_joe();
     if (fred_gives_up()) break;
}

Continue is a little different than break. When you call continue it goes back to the top of the loop and runs again.

Note: Whether or not you are using a while or a do ... while it will check the condition before running again.

Here's an example. A robot is trying to get to a finish line but there are cones in his way:

//this code is theoretical since these functions don't exist
while (not_at_finish_line()) {
     go_forward();
     if (no_obstructions()) continue;
     go_around_obstruction();
}

Little-Known Clever Trick

With a combined knowledge of do ... while loops and break statements we can create a scenario where we can skip lines of code if we want to. What we do is create a do ... while where no matter what it only runs once. This gives us the chance to skip subsequent lines of code if we want to. Here's an example:

do {
     // run some code
     if (we_want_to_skip()) break;
     // do some more stuff
     if (we_want_to_skip_more()) break;
     // do even more stuff
} while (false);

This isn't always the best way. Sometimes if statements work best or return if you're in a function.

How to Know Which One to Use

The rule I tend to go by to know which statement or method I should use is by using the following rules:

  1. Am I repeating or copying/pasting code I already used?
  2. Which way uses less lines of code

There are times when using more lines of code is more efficient but you should never repeat yourself when coding

That's it for this tutorial. Happy Coding!

Tags: , , , ,

This entry was posted on Monday, April 19th, 2010 at 4:46 pm and is filed under Programming, Tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

6 Responses to “Do While vs While”

  1. Wow, Chris, I like your emphasis on clean, light, and fast code.

  2. Will B. says:

    dang sweet info bro.

  3. Bonny Nordman says:

    Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! I’m sure you had fun writing this article.

  4. Garfield Lisa says:

    I saw many websites but yours is awsome, bookmarked for future referrence.

  5. Harris Morrill says:

    Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

  6. Robert from usa onlinecasino says:

    Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Leave a Reply