Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - BREAK


Break as the name suggests, is used to break out of a loop(i.e. for loop) before its execution is complete.


To make it a little simpler, let us take the below example.


'Break' with 'for loop'


Say you have a for loop that is used to print the numbers from 1 to 5.


Example :



public class MyApplication
{
    public static void Main(string[] args)
    {
     	for(int x = 1; x <= 5 ; x++) 
     	{
          System.Console.WriteLine(x);
       	}
    }
}


Output :



  1
  2
  3
  4
  5

But let us say, you want to break out of the for loop, if the value of x is 3. i.e. You want to get out of the loop, right after printing 1, 2 and 3.


And we can achieve it using break statement.


Let us modify the above program using the break statement.


Example :



public class MyApplication
{
    public static void Main(string[] args)
    {
     	for(int x = 1; x <= 5 ; x++) 
     	{
            System.Console.WriteLine(x);
      	    if (x == 3) {
 			    break;
 		    }
       	}
    }
}


Output :



  1
  2
  3

And all we have done is placed an if condition, right after the print statement, checking if the value of x is equal to 3. If so we break out of the loop.


if (i == 3) {
	break;
}

And the break statement helps to get out of the for loop.