#166 – Using the for Statement to Create an Infinite Loop

You can create an infinite loop using either while or for.

In the example below, the body of the for loop will run forever.

            // Run forever
            for (;;)

You can accomplish the same thing using while (true), but you might still use the for loop if you want to use a loop variable.

            // Run forever
            for (uint questionNumber = 1; ; questionNumber++)

#165 – Any Clause of the for Loop May Be Left Empty

Any of the three clauses of the for loop may be left empty.

If the initialization clause is left empty, no initialization is done before the loop starts executing for the first time.

            // Loop until i reaches 10, no matter what its starting value
            for (; i <= 10; i++)

If the condition clause is empty, no condition is ever checked to determine when the loop should exit and the loop executes forever.

            // Loop forever, incrementing i
            for (int i = 0; ; i++)

The iteration clause can also be empty.

            // Get 'er done, Hercules
            for (int laborNum = 1; laborNum <= 12; )
                bool success = HerculesLabors(laborNum);
                if (success == true)

#164 – for Loop Clauses Can Contain Lists of Statements

Both the initialization clause and the iteration clause of a for loop can consist of multiple statements, separated by commas.

For example, you could initialize two different variables in the initialization clause and then increment one variable and decrement the other in the iteration clause.

            // Set reverse diagonal of matrix
            for (int i = 0, j = 9;
                 i < 10;
                 i++, j--)
                nums[i, j] = 1;

#163 – Iterating Using the for Loop

The for statement allows executing a block of code a fixed number of times.

You could use a while loop to execute a block of code a fixed number of times:

            int i = 1;
            int sum = 0;

            // Add up numbers 1-10
            while (i <= 10)
                sum += i;

You can do this a little more conveniently using a for loop.

            int sum = 0;

            // Add up numbers 1-10
            for (int i = 1; i <= 10; i++)
                sum += i;

The expression after the for keyword includes three clauses, separated by a semicolon:

  • The initialization clause specifies variables to initialize before the loop starts executing
  • The condition clause specifies the conditions under which the loop continues to execute
  • The iteration clause specifies an operation to perform after executing the body of the loop

#162 – do/while Loop Executes At Least Once

Similar to the while loop is the do/while loop, which executes at least once and tests a conditional expression at the end of the loop to determine whether to continue iterating.

In the example below, we first make one pass through the loop, raking leaves.  After executing the loop once, we count the remaining leaves on the lawn to determine if we need to continue raking and bagging.

            uint numLeavesOnLawn;

            // Rake first, count leaves later
                numLeavesOnLawn = CountLeaves();
            } while (numLeavesOnLawn > 50);

Like the while loop, you can exit a do/while loop on break, goto, return or throw statements.

Like the while loop, you can proceed immediately with the next iteration using the continue statement.

#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)
                bool seemsInteresting = ReadBackCover();
                if (!seemsInteresting)
                    continue;    // continue with next book

#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

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)

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)

#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)
                numLeavesOnLawn = CountLeaves();

#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)
                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");