#1,126 – Rewriting a Loop to Avoid continue Statement

The continue statement allows jumping to end of the body of a loop, skipping the rest of the code within the loop.  Either the next iteration of the loop executes, or the code following the loop statement executes.

            List<Dog> myDogs = new List<Dog>
            {
                new Dog {Name = "Kirby", Age = 5},
                new Dog {Name = "Jack", Age = 17},
                new Dog {Name = "Ruby", Age = 2}
            };

            foreach (Dog d in myDogs)
            {
                if (d.Age > 15)
                    continue;

                Console.WriteLine("{0} doing a trick", d.Name);
                d.DoATrick();
            }

1126-001
In most cases, you can rewrite the body of a loop and avoid using a continue statement by using an if statement.  The end result is generally more readable.

            foreach (Dog d in myDogs)
            {
                if (d.Age <= 15)
                {
                    Console.WriteLine("{0} doing a trick", d.Name);
                    d.DoATrick();
                }
            }
Advertisement

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

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

#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