The break and continue statement
The break, continue statements
The break statement can be used to terminate a block defined by while, for or switch statements.
using System;
public class CSharpApp
{
static void Main()
{
Random random = new Random();
while (true)
{
int num = random.Next(1, 30);
Console.Write(num + ” “);
if (num == 22)
break;
}
Console.Write(‘\n’);
}
}
We define an endless while loop. We use the break statement to get out of this loop. We choose a random value from 1 to 30. We print the value. If the value equals to 22, we finish the endless while loop.
$ ./break.exe
29 21 26 6 29 3 10 3 18 6 3 22
We might get something like this.
The continue statement is used to skip a part of the loop and continue with the next iteration of the loop. It can be used in combination with for and while statements.
In the following example, we will print a list of numbers, that cannot be divided by 2 without a remainder.
using System;
public class CSharpApp
{
static void Main()
{
int num = 0;
while (num < 1000)
{
num++;
if ((num % 2) == 0)
continue;
Console.Write(num + ” “);
}
Console.Write(‘\n’);
}
}
We iterate through numbers 1..999 with the while loop.
if ((num % 2) == 0)
continue;
If the expression num % 2 returns 0, the number in question can be divided by 2. The continue statement is executed and the rest of the cycle is skipped. In our case, the last statement of the loop is skipped and the number is not printed to the console. The next iteration is started.