C# break statement

In C# using break statement, we can exit from any loop like for loop, while loop or do-while loop. break statement can be used, when while executing code inside the loop, you want to exit if certain condition is true.

When break statement is encountered inside the loop, then loop is immediately termindated or loop is no more executed and next statement after loop is executed.

Syntax:

break;

Example:

    using System;  
    public class DoWhileLoopWithBreakExample  
        {  
          public static void Main(string[] args)  
          {  
              int i = 1;  
                
              do{  
                  Console.WriteLine(i);  
                  
				  //check if value of i is 5
				  if(i==5)
				  {
					  //if value of i is 5, exit from loop and it will not print remaining values
					  break;
				  }
				  i++;  
              } while (i <= 10) ;  
			  
			  Console.Write("After loop ends");
        
         }  
       }  

In the above statement, as soon as value i reaches to 5, do-while loop is terminated and next statement of code Console.Write("After loop ends"); is executed.

Output:

1
2
3
4
5
After loop ends

Break statement inside nested for loop

Suppose, we have nested for loops, then break statement will exit from the loop, inside which it is placed and other outer for loop may continue.

Example:

using System;
					
public class BreakInsideNestedForProgram
{
	public static void Main()
	{
		for(int i=1; i <= 3; i++)
		{
			for(int j=1; j <= 3; j++)
			{
				// if value of j =2 , exit from inner loop
				if(j==2)
				{
					break;
				}
				Console.WriteLine(i +" "+j );
			}
			Console.WriteLine("End of loop number "+i+" for i");
		}
	}
}

Output:

1 1
End of loop number 1 for i
2 1
End of loop number 2 for i
3 1
End of loop number 3 for i

As you can see from the output, value of j was never printed as 2, because we were breaking the inner loop, whenever it was equal to 2.


Share Tweet