#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 (;;)
            {
                AskUserATriviaQuestion();
                TellThemTheCorrectAnswer();
            }

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++)
            {
                AskUserATriviaQuestion(questionNumber);
                TellThemTheCorrectAnswer(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++)
            {
                Console.WriteLine(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++)
            {
                Console.WriteLine(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)
                    laborNum++;
            }

#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;
                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
            do
            {
                RakeLeaves();
                FillNextBag();
                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)
            {
                SelectNextBook();
                BuyNextBook();
                bool seemsInteresting = ReadBackCover();
                if (!seemsInteresting)
                    continue;    // continue with next book
                ReadTheBook();
                TellFriendsAboutBook();
                booksIWantToRead--;
            }

#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.