Use of Break satement in C#
in the C# language we use break Statement for exit from loop without complete execution of loops.we can use Break statement with all loop statements that use in C# like as for loop,while loop,do while loop,for each loop and switch statment.
Use of Break Statement in C#
In C# and another programming languages,loops are use for perform repeatedly set of operations.The break statement use in C# for break loop execution.
The break statement used for exit from loop without complete execution of for loops.We can use Break Statement with for loop,While loop ,do while loop,for each loop and switch statement.Break statement must be enclosed in the loop blocks otherwise error will be generated.
In this code i will show you working of Break Statement in C#.here we will use break statement with for loop
using System;
using System.Collections.Generic.
using System.Text;
namespace Csharpbreak
{
class Program
{
static void Main(string[] args)
{
for(int x=0; x<4;x++)
{
Console.WriteLine(x);
if(x==2)
break;
}
}
}
}
IN THIS CODE WE SET BREAK STATEMENT WHEN FOR LOOP RUN TWO TIMES AND X VALUE INCREMENT 2.
OUTPUT WILL BE LIKE AS GIVEN BELLOW:
0
1
2
Press any key to conitnue...
The break statement in C# has following two usage:
1. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement.
If you are using nested loops ( ie. one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
Syntax:
The syntax for a break statement in C# is as follows:
break;