Utilizor
Contact Us

C# Break/Continue

Controlling loop execution.

C# Break and Continue

Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

Examples

Break Example

Stops the loop when i is 4.

using System;

class Program
{
  static void Main(string[] args)
  {
    for (int i = 0; i < 10; i++) 
    {
      if (i == 4) 
      {
        break;
      }
      Console.WriteLine(i);
    }
  }
}

Continue Example

Skips printing 4.

using System;

class Program
{
  static void Main(string[] args)
  {
    for (int i = 0; i < 10; i++) 
    {
      if (i == 4) 
      {
        continue;
      }
      Console.WriteLine(i);
    }
  }
}

Break in While Loop

Using break in a while loop.

using System;

class Program
{
  static void Main(string[] args)
  {
    int i = 0;
    while (i < 10) 
    {
      Console.WriteLine(i);
      i++;
      if (i == 4) 
      {
        break;
      }
    }
  }
}

Continue in While Loop

Using continue in a while loop (careful with increment!).

using System;

class Program
{
  static void Main(string[] args)
  {
    int i = 0;
    while (i < 10) 
    {
      if (i == 4) 
      {
        i++;
        continue;
      }
      Console.WriteLine(i);
      i++;
    }
  }
}

Break Inner Loop

Break only affects the loop it is inside.

using System;

class Program
{
    static void Main()
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (j == 1) break; // Breaks inner loop only
                Console.WriteLine("i=" + i + " j=" + j);
            }
        }
    }
}