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. For example:
// Using break with nested loops.
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
Do'stlaringiz bilan baham: |