#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

#157 – Iterating Using the while Loop

The while loop allows you to execute a single statement or block of code 0 or more times, continuing to execute while a particular expression evaluates to true.  The expression can be a single boolean variable or a more complicated expression that evaluates to a boolean result.

Here’s an example.

            bool keepPlaying = true;

            // Display trivia until user wants to quit
            while (keepPlaying)
            {
                DisplaySomeTrivia();
                keepPlaying = AskUserIfTheyWantToContinue();
            }

The braces denote the block of code that will be executed repeatedly.  Since the keepPlaying variable starts out true, the code will be executed at least once.  AskUserIfTheyWantToContinue will ask the user if they want to continue and return a true or false value.  So the loop will execute until the user decides to stop.

Another example:

            int numTimesPrinted = 0;

            // Print something out 100 times
            while (numTimesPrinted < 100)
            {
                Console.WriteLine("I will not pull Sally's pigtails");
                numTimesPrinted++;
            }