#167 – Use continue to Jump to Next Iteration of for Loop

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

            // Compute/display some factorials
            for (long i = 1; i <= 20; i++)
            {
                // I'm superstitious--avoid 13!
                if (i == 13)
                    continue;

                Console.WriteLine(string.Format("Factorial of {0} is {1}", i, FactorialOf(i)));
            }
Advertisements

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