C# break statement
In this chapter you will learn:
- What is break statement
- How to create break statement
- Example for break statement
- break statement with while loop
- Find the smallest factor of a value
- Using break with nested loops
- Use break with a foreach
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 av a 2 s .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;/*from w ww . jav a 2 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; // w w w . j a va 2 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; /* www. j av a2 s. co 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; //from w w w .j a v a 2 s. c o m
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.
Next chapter...
What you will learn in the next chapter:
- What is continue statement
- How to create continue statement
- Example for continue statement
- continue within if statement