Thursday 19 July 2012

CONTINUE


Continue alters control flow. It is used most often in loop bodies in the C# language. The continue keyword allows you to skip the execution of the rest of the iteration. It jumps immediately to the next iteration in the loop. This keyword is most useful in while loops.
Example
Note

To begin, let's look at a program that uses the continue statement in a while-true loop. In a while-true loop, the loop continues infinitely with no termination point. In this example, we use a Sleep method call to make the program easier to watch as it executes.

A random number is acquired on each iteration through the loop, using the Next method on the Random type. Then, the modulo division operator is applied to test for divisibility by 2 and 3. If the number is divisible, then the rest of the iteration is aborted, and the loop restarts.

Program that uses continue keyword

using System;
using System.Threading;

class Program
{
    static void Main()
    {
          Random random = new Random();
          while (true)
          {
              // Get a random number.
              int value = random.Next();
              // If number is divisible by two, skip the rest of the iteration.
              if ((value % 2) == 0)
              {
                   continue;
              }
              // If number is divisible by three, skip the rest of the iteration.
              if ((value % 3) == 0)
              {
                   continue;
              }
              Console.WriteLine("Not divisible by 2 or 3: {0}", value);
              // Pause.
              Thread.Sleep(100);
          }
    }
}

Output

Not divisible by 2 or 3: 710081881
Not divisible by 2 or 3: 1155441983….

No comments:

Post a Comment