#161 – Use continue to Jump to Next Iteration of While Loop

Within a while loop, you can use the continue statement to stop executing the current iteration of the loop and continue with the next iteration.

            while (booksIWantToRead > 0)
            {
                SelectNextBook();
                BuyNextBook();
                bool seemsInteresting = ReadBackCover();
                if (!seemsInteresting)
                    continue;    // continue with next book
                ReadTheBook();
                TellFriendsAboutBook();
                booksIWantToRead--;
            }
Advertisement

#160 – A while Loop Can Exit on break, goto, return or throw Statements

In addition to completing normally, when the loop expression evaluates to false, a while loop can exit early.  A loop will exit early if it encounters one of the following statements: break, goto, return or throw.

A break statement causes an early exit of the loop and execution to continue with the first statement after the loop.

            uint numTimes = 0;
            while (numTimes < 100)
            {
                WriteOnBlackboard("I will not eat paste");
                if (ChalkBroke())
                    break;     // Stop writing
                numTimes++;
            }

The goto statement can transfer control out of a while loop, to a labeled statement.  Its use is rare, since there are generally more elegant ways to transfer control.

The return statement can transfer control out of a loop and return control to the calling method.

The throw statement transfers control out of a loop and throws an exception, indicating that an error condition occurred.

#159 – A while Loop Might Execute Forever

If the boolean expression that controls a while loop never evaluates to false, the loop might continue to execute indefinitely.  This is known as an infinite loop.

You might create an infinite loop by design, or it might in fact be a programming error.  The only way to end an infinite loop is to kill the parent process.

In the following example, we just use the value of true for the loop expression, so that the loop will continue to execute indefinitely.

            uint digit = 1;

            while (true)
            {
                CalculateNthDigitOfPi(digit);
                RecordNthDigitOfPi(digit);
                digit++;
            }

In the example below, we intend for Sisyphus to roll his rock up the hill ten times.  We intend to decrement the numRolls variable, but mistakenly increment it.  This leads to an infinite loop, with Sisyphus doomed to roll his rock up the hill forever.

            uint numRolls = 10;

            while (numRolls > 0)
            {
                SisyphusRollRockUphill();
                numRolls++;
            }

#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++;
            }