Csharp/CSharp Tutorial/Statement/Break

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Find the smallest factor of a value

using System; 
 
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);  
  }  
}
Smallest factor is 2

Use break with a foreach.

using System; 
 
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); 
  } 
}
Value is: 0
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Summation of first 5 elements: 10

Using break to exit a do-while loop

using System; 
 
class MainClass {  
  public static void Main() {  
    int i; 
 
    i = -10;     
    do { 
      if(i > 0) 
         break; 
      Console.Write(i + " "); 
      i++; 
    } while(i <= 10); 
  
    Console.WriteLine("Done");  
  }  
}
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 Done

Using break to exit a for loop

using System; 
 
class MainClass {  
  public 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");  
  }  
}
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 Done

Using break with nested loops

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