#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();
            }
Advertisement