#158 – A while Loop Expression Is Evaluated Before Executing the Loop

Because the expression used in a while loop is tested before the loop is executed, it’s possible that the loop won’t be executed at all.

In the following example, we count the number of leaves on our lawn and then only rake and bag if we see more than 50 leaves.  When done filling a bag, we count again and then go back to the top of the loop, where we’ll decide whether we should keep raking.  It’s possible, however, that the lawn is empty of leaves to start with and in that case, we wouldn’t execute the loop at all.

            numLeavesOnLawn = CountLeaves();
            while (numLeavesOnLawn > 50)
            {
                RakeLeaves();
                FillNextBag();
                numLeavesOnLawn = CountLeaves();
            }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: