break
In this chapter you will learn:
- How to use break statement
- break statement with while loop
- Find the smallest factor of a value
- Using break with nested loops
- Use break with a foreach
Using break statement
break
statement is used to jump out of a loop for a switch.
The following code terminates the for loop by using the break
statement.
using System;// ja va2s. 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:
break statement with while loop
We can also use break statement to jump out of a while loop.
using System;/*j a va 2 s . c om*/
class Program
{
static void Main(string[] args)
{
int i = 10;
while (i > 0)
{
Console.WriteLine(i);
if (i == 5)
{
break;
}
i--;
}
}
}
The output:
Find the smallest factor of a value
using System; //ja v a2s . 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.
Using break with nested loops
using System; /* jav a 2 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.
Use break with a foreach
using System; /*j av a 2s . 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: