C# – Break/Continue

Break

The C# break is used to break loop or switch statement. It breaks the current flow of the program at the given condition. In case of inner loop, it breaks only inner loop.

// Using break to exit a loop.
 using System; 
 class BreakDemo {
 static void Main() {
 // Use break to exit this loop.
 for(int i=-10; i <= 10; i++) {
 if(i > 0) break; 
 // terminate loop when i is positive
 Console.Write(i + " ");   
 }   
 Console.WriteLine("Done");  

This program generates the following output: -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 Done

As you can see, although the for loop is designed to run from –10 to 10, the break statement causes it to terminate early, when i becomes positive.

The break stops the for loop as soon as a factor is found. The use of break in this situation prevents the loop from trying any other values once a factor has been found, thus preventing inefficiency. When used inside a set of nested loops, the break statement will break out of only the innermost loop.

using System; 
class BreakNested {
  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."); 
  } 
} 

This program generates the following output:
Outer loop count: 0
Inner loop count: 0 1 2 3 4 5 6 7 8 9
Outer loop count: 1
Inner loop count: 0 1 2 3 4 5 6 7 8 9
Outer loop count: 2
Inner loop count: 0 1 2 3 4 5 6 7 8 9
Loops complete.
As you can see, the break statement in the inner loop causes only the termination of that loop. The outer loop is unaffected. Here are two other points to remember about break: First, more than one break statement may appear in a loop. However, be careful. Too many break statements have the tendency to destructure your code. Second, the break that exits a switch statement affects only that switch statement and not any enclosing loops.

Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. The continue statement forces the next iteration of the loop to take place, skipping any code in between. Thus, continue is essentially the complement of break. For example, the following program uses continue to help print the even numbers between 0 and 100.

using System; 
class ContDemo {
  static void Main() {
  // Print even numbers between 0 and 100.
  for(int i = 0; i <= 100; i++) {
  if((i%2) != 0) continue; 
  // iterate      
  Console.WriteLine(i);
  }  
 } 
} 
0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x