C# break statement
Description
break
statement is used to jump out of a loop for a switch.
Syntax
To end the execution:
break;
Example
The following code terminates the for loop by using the break
statement.
using System;//from w w w. j a v a 2s.c o m
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}
The output:
Example 2
We can also use break statement to jump out of a while loop.
using System;// w w w . j a va2 s. c o m
class Program
{
static void Main(string[] args)
{
int i = 10;
while (i > 0)
{
Console.WriteLine(i);
if (i == 5)
{
break;
}
i--;
}
}
}
The output:
Example 3
using System; //from www .j av a2 s . c o m
class MainClass {
public static void Main() {
int factor = 1;
int num = 1000;
for(int i=2; i < num/2; i++) {
if((num%i) == 0) {
factor = i;
break; // stop loop when factor is found
}
}
Console.WriteLine("Smallest factor is " + factor);
}
}
The code above generates the following result.
Example 4
using System; /*from w w w. j a va 2 s . c o m*/
class MainClass {
public static void Main() {
for(int i=0; i<3; i++) {
Console.WriteLine("Outer loop count: " + i);
Console.Write(" Inner loop count: ");
int t = 0;
while(t < 100) {
if(t == 10)
break; // terminate loop if t is 10
Console.Write(t + " ");
t++;
}
Console.WriteLine();
}
Console.WriteLine("Loops complete.");
}
}
The code above generates the following result.
Example 5
using System; //w ww .j a v a 2 s.com
class MainClass {
public static void Main() {
int sum = 0;
int[] nums = new int[10];
for(int i = 0; i < 10; i++)
nums[i] = i;
foreach(int x in nums) {
Console.WriteLine("Value is: " + x);
sum += x;
if(x == 4)
break; // stop the loop when 4 is obtained
}
Console.WriteLine("Summation of first 5 elements: " + sum);
}
}
The code above generates the following result.